any number between -128 and 127, the JDK create a cache :
static class valueOfCache {
/**
* A cache of instances used by {@link Integer#valueOf(int)}
* and auto-boxing.
*/
static final Integer[] CACHE = new Integer[256];
static {
for(int i=-128; i<=127; i++) {
CACHE[i+128] = new Integer(i);
}
}
}
And the static valueOf() method:
/*If it is not necessary to get a new {@code Integer}
*instance,it is recommended to use this method instead
*of the constructor,since it maintains a cache of
*instances which may result in better performance.
*/
public static Integer valueOf(int i) {
if (i < -128 || i > 127) {
return new Integer(i);
}
return valueOfCache.CACHE [i+128];
}
Sometime this method gives a better performance,
but there are a lot of debates here.
No comments:
Post a Comment