Does comparing an int and long hurt performance? i.e.
int x = 1;
long y = 2;
if (x < y) doStuff();
as opposed to:
int x = 1;
int y = 2;
if (x < y) ...
Is there a conversion of types? or does the layout of bits in memory allow a straight comparison? (i.e. the extra bits in the long can all assumed to be 0 for an int)
@WeishiZeng: Yes, absolutely. Both operands in a + 1 are int - so that addition happens in int arithmetic, then the conversion to long , then the comparison.
Use int when possible, and use Integer when needed. Since int is a primitive, it will be faster. Modern JVMs know how to optimize Integer s using auto-boxing, but if you're writing performance critical code, int is the way to go.
Primitive type int needs 4 bytes in Java but, Integer object occupies 16 bytes of memory. Hence, int is comparatively faster than an Integer object. Since, int is a primitive type it is less flexible.
The type long is used where the type int is not that large to hold the desired value. The range of long is –9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 which is quite large, to hold the larger values like big whole numbers.
The Java Language Specification says that binary numeric promotion occurs and the int
therefore is converted to a long
. In practice the conversion is really trivial - it's not an expensive operation on most modern hardware. However, this whole issue shouldn't really be a performance concern; you use a long not because of performance, but because you need to be able to manage larger numeric values.
And as always with performance questions, the real answer is that:
a) you shouldn't worry about performance until it becomes an issue
b) at that stage you should profile or conduct measurements to see what the effect is.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With