Which is better: let Java do autoboxing or use valueOf ()

I'm just wondering if there is any difference in letting java autobox say an integer:

Integer myInteger = 3; // This will call Integer.valueOf() 

or having your code like

 Integer myInteger = Integer.valueOf(3); 

Is there any micro optimization? I know that the second is more explicit, but it is also a more unnecessary typing, is there any difference besides this?

+17
java performance autoboxing
Mar 09 2018-11-11T00:
source share
3 answers

They are equal in any case internally, so use the first option. Most likely, future compiler optimizations may make the first even faster in the future.

+18
Mar 09 2018-11-11T00:
source share

I would choose the first choice. This is the same with less code.

If I do not expect the program to run on an older version of the JVM. However, in this case, this will not be the only compatibility issue.

Thus, the only reason not to use autoboxing is if it is not available.

+4
Mar 09 2018-11-11T00:
source share

What I know, there really isn’t much performance difference here , see this post here The difference is not really a difference, but you should use valueOf because Integer now caches Integer objects between -128 and 127.

+1
Mar 09 2018-11-11T00:
source share



All Articles