What is faster: equal check or sign check

90 views Asked by At

I wonder which operation works faster:

int c = version1.compareTo(version2);

This one

if (c == 1)

or this

if (c > 0)

Does sign comparasion use just a one bit check and equality comparasion use substraction, or it is not true? For certainty, let's say we work on x86.

P.S. Not an optimization issue, just wondering how it works.

2

There are 2 answers

10
Stefano Sanfilippo On BEST ANSWER

Assuming those operations are JITted into x86 opcodes without any optimization, there is no difference. A possible x86 pseudo-assembly snippet for the two cases could be:

cmp i, 1
je destination

and:

cmp i, 0
jg destination

The cmp operation performs a subtraction between the two operands (register i and immediate 0), discards the result and sets some flags: positive, negative, overflow etc.

These flags are then used to trigger a conditional jump (i.e. jump if condition), in one case if the two operands are equal, in the second case if the first is greater than the second.

Again, this without considering any software (JVM-wise) and/or hardware optimization. In fact, x86_64 architectures have a complex pipeline with advanced branch-prediction and out-of-order execution, for which these microbenchmarks are almost meaningless. We are long past counting instructions.

2
Stephen C On

"How it works" really depends on the platform (e.g. the hardware instruction set), the version of Java that you are using, and the context (e.g. what happens before and after in the program.)

For what it is worth, there is a java command-line option that will dump out the JIT compiled native code for a particular method:

However, you should be aware that the two tests are not equivalent. Specifically, a Comparable<T>.compareTo(T) method is not guaranteed to return -1, 0 or +1. The spec says that it can return any integer. Hence testing for c == 1 may not work ... depending on how compareTo is implemented.