Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does int vs long comparison hurt performance in Java?

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)

like image 521
talloaktrees Avatar asked Dec 31 '13 05:12

talloaktrees


People also ask

Can we compare long and int in Java?

@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.

Is integer less efficient than int Java?

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.

Which is faster int or integer?

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.

Why would you use a type long for a variable instead of type int?

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.


1 Answers

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.

like image 96
davmac Avatar answered Sep 28 '22 17:09

davmac