What is the performance difference between Integer.valueOf()
and Autoboxing?
This is my below code:
int value = 5;
//1 Integer.valueOf()
Integer result = Integer.valueOf(5);
//2 Autoboxing
Integer result = value;
Note: I need Integer Object. Ex: use it as a key in a HashMap< Integer,String>
I don't know why and which is faster? Integer.valueOf()
(1) or Autoboxing (2).
About (1) I check java code of Integer.valueOf()
. There seem they get Integer
object from cache.
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
About (2) I heard that JVM has its own Integer
pool to reuse Integer
object.
I try to understand but still don't know why and which is faster?