compareTo with primitives -> Integer / int
Is it better to write
int primitive1 = 3, primitive2 = 4;
Integer a = new Integer(primitive1);
Integer b = new Integer(primitive2);
int compare = a.compareTo(b);
or
int primitive1 = 3, primitive2 = 4;
int compare = (primitive1 > primitive2) ? 1 : 0;
if(compare == 0){
compare = (primitive1 == primitive2) ? 0 : -1;
}
I think the second one is better, should be faster and more memory optimized. But aren't they equal?
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 7
int 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.