Reputation: 704
According to the Java Language Specification, section 5.1.7, Java caches Integer
s from -128 to 127 for performance optimization.
So when you compare a == b
, with a
& b
Integers in the caching range, it returns true even though they're different objects.
Mechanically, what performance benefits result from this caching? According to this answer, "The purpose is mainly to save memory, which also leads to faster code due to better cache efficiency." How does it lead to faster code? How might I use this feature to improve performance in real code I write?
Does it have anything to do with the following method found in the IntegerCache
class?
public static Integer valueOf(int i) {
assert IntegerCache.high >= 127;
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
Upvotes: 1
Views: 361
Reputation: 718788
The performance benefit is nothing to do with ==
. The real reason is that the cache allows valueOf
to avoid creating lots of objects when the same "small" integers are boxed repeatedly. Integer
objects occupy space (at least 16 bytes). Creating lots of them means that the garbage collector needs to run more frequently.
My understanding is that the Java team did a lot of analysis of real-world applications, and came to the conclusion that the Integer
cache was a worthwhile optimization.
(The reason I say that it is nothing to do with ==
is that you cannot rely on ==
working for Integer
objects. Therefore, any code that does this ... without also ensuring that the integers are in the specified range ... is buggy. And if you do a range check to ensure that the numbers are in-range, you are likely to spend more on that than you save by using ==
.)
"... which also leads to faster code due to better cache efficiency." How does it lead to faster code?
The cache efficiency they are talking about is the hardware level memory cache that most modern processors use to deal with the mismatch between CPU and memory speeds. If the application has only one Integer
object representing the number 1
and that number appears frequently, then the chances that the memory addresses holding the 1
object are in the (memory) caches are increased. Cache hits means faster code.
Does it have anything to do with the following method found in the IntegerCache class?
Erm ... yes.
Upvotes: 7