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);
}