Autoboxing versus manual boxing in Java

后端 未结 3 1701
终归单人心
终归单人心 2020-12-05 08:00

Why is the second piece of code faster?

Map map = new HashMap();
for (int i = 0; i < 50000; i++) {
    for (         


        
3条回答
  •  长情又很酷
    2020-12-05 08:22

    Autoboxing will use Integer.valueOf and Double.valueOf. There is some overhead in calling those methods (although it will eventually get inlined). Also Integer.valueOf does some checking for low-values to use pooled instances, which is not frequently a win in your code (although it could reduce heap size a little). Pooled instances may be a win where they reduce heap size, GC times and could even improve equality test performance..

    But, in general, it's a microoptimisation which you should, in general, ignore.

提交回复
热议问题