Hieu Tran
Hieu Tran

Reputation: 53

What is performance difference between Integer.valueOf() and Autoboxing

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?

Upvotes: 4

Views: 1145

Answers (1)

maaartinus
maaartinus

Reputation: 46422

This question is strongly related to this question. As already said in the comments and in the answer to the linked question,

autoboxing invokes the static method Integer.valueOf(), and autounboxing invokes intValue() on the given Integer object. There's nothing else, really - it's just syntactic sugar.

Obviously, the performance is the same. However, things are a bit more complicated as this answer says:

there is no guarantee of how autoboxing is internally implemented.

So, in theory, given some exotic java compiler, the implementation might differ and so might the performance. Practically, there's no reason for implementing autoboxing differently. Moreover, if there was a better implementation, it probably could be incorporated into Integer.valueOf(). So even then, the performance would be the same.


In Java, there's usually nothing to gain from using an alternate implementation doing the same. For example, there used to be performance differences between Arrays.copyOf and System.arraycopy, but AFAIK they were optimized away in the Oracle / OpenJDK JVM.

Upvotes: 4

Related Questions