compareTo with primitives -> Integer / int compareTo with primitives -> Integer / int java java

compareTo with primitives -> Integer / int


For performance, it usually best to make the code as simple and clear as possible and this will often perform well (as the JIT will optimise this code best). In your case, the simplest examples are also likely to be the fastest.


I would do either

int cmp = a > b ? +1 : a < b ? -1 : 0;

or a longer version

int cmp;if (a > b)   cmp = +1;else if (a < b)   cmp = -1;else   cmp = 0;

or

int cmp = Integer.compare(a, b); // in Java 7int cmp = Double.compare(a, b); // before Java 7

It's best not to create an object if you don't need to.

Performance wise, the first is best.

If you know for sure that you won't get an overflow you can use

int cmp = a - b; // if you know there wont be an overflow.

you won't get faster than this.


Use Integer.compare(int, int). And don'try to micro-optimize your code unless you can prove that you have a performance issue.


May I propose a third

((Integer) a).compareTo(b)