Difference between if (a – b < 0) and if (a < b)

I was reading Java’s ArrayList source code and noticed some comparisons in if-statements.

In Java 7, the method grow(int) uses

if (newCapacity - minCapacity < 0)
    newCapacity = minCapacity;

In Java 6, grow didn’t exist. The method ensureCapacity(int) however uses

if (newCapacity < minCapacity)
    newCapacity = minCapacity;

What was the reason behind the change? Was it a performance issue or just a style?

I could imagine that comparing against zero is faster, but performing a complete subtraction just to check whether it’s negative seems a bit overkill to me. Also in terms of bytecode, this would involve two instructions (ISUB and IF_ICMPGE) instead of one (IFGE).

4 Answers
4

Leave a Comment