19

I am just wondering is there any difference in letting java autobox say an integer:

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

or having your code as

Integer myInteger = Integer.valueOf(3);

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

4

3 に答える 3

19

They are equal anyway internally, so use the first variant. Chances are good, that future compiler optimizations may make the first even faster in the future.

于 2011-03-09T22:51:41.957 に答える
4

I'd use the first choice. It's the same thing with less code.

Unless I expect that the program would have to run on an older version of JVM. However, in that case this would be far from being the only compatibility issue.

So, the only reason not to use autoboxing is if it's not available.

于 2011-03-09T22:56:34.577 に答える
1

That I know, there really isn't a huge difference in performance see this post here The difference isn't really a difference, but you should use valueOf, because Integer now caches Integer objects between -128 and 127.

于 2011-03-09T22:57:54.600 に答える