2

我看到了下面的代码,想知道编码器的意图。它是自动装箱的相关性能吗?

map.put("doesntMatter", Boolean.TRUE);

他本可以这样做:

map.put("doesntMatter", true);

做第一个有什么好处吗?

4

2 回答 2

5

我写了一个例子:

public class Demo {

    Map<String, Boolean> map = new HashMap<>();

    void primitive() {
        map.put("a", true);
    }

    void object() {
        map.put("b", Boolean.TRUE);
    }
}

看字节码primitive()

 0 aload_0
 1 getfield #17 <Demo/map Ljava/util/Map;>
 4 ldc #24 <a>
 6 iconst_1
 7 invokestatic #26 <java/lang/Boolean/valueOf(Z)Ljava/lang/Boolean;>
10 invokeinterface #32 <java/util/Map/put(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;> count 3
15 pop
16 return

和字节码object()

 0 aload_0
 1 getfield #17 <Demo/map Ljava/util/Map;>
 4 ldc #39 <b>
 6 getstatic #41 <java/lang/Boolean/TRUE Ljava/lang/Boolean;>
 9 invokeinterface #32 <java/util/Map/put(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;> count 3
14 pop
15 return

结论:

使用原语时,有一个额外的步骤调用Boolean.valueOf(),但如果你经常运行那段代码,JIT 编译器会完成它的工作并优化它。

于 2013-06-21T18:34:59.243 回答
1

好处不在于执行时间,因为这个小测试代码显示:

结果 :

Time with primitives : 3334779619
Time with Object : 4092034749
Time with primitives : 3670851766
Time with Object : 2748035018
Time with Object : 3738916372
Time with primitives : 2975196722
Time with Object : 2514328271
Time with primitives : 2588980283
Time with Object : 2696162369
Time with primitives : 2615258656
Time with primitives : 2633824223
Time with Object : 2489779261

代码 :

import java.util.HashMap;
import java.util.Map;

import javax.swing.JOptionPane;

public class Test
{
  public static void main(String[] args) {
    JOptionPane.showMessageDialog(null, "Start");

    createWithPrimitive();
    createWithObject();
    createWithPrimitive();
    createWithObject();
    createWithObject();
    createWithPrimitive();
    createWithObject();
    createWithPrimitive();
    createWithObject();
    createWithPrimitive();
    createWithPrimitive();
    createWithObject();

    System.exit(0);
  }

  private static void createWithObject() {
    long time = System.nanoTime();
    Map<Integer, Boolean> testMap = new HashMap<Integer, Boolean>();
    for (int i = 1; i <= 10000000; i++) {
      if (i % 2 == 0) {
        testMap.put(i, Boolean.TRUE);
      } else {
        testMap.put(i, Boolean.FALSE);
      }
    }

    System.out.println("Time with Object : " + (System.nanoTime() - time));
  }

  private static void createWithPrimitive() {
    long time = System.nanoTime();
    Map<Integer, Boolean> testMap = new HashMap<Integer, Boolean>();
    for (int i = 1; i <= 10000000; i++) {
      if (i % 2 == 0) {
        testMap.put(i, true);
      } else {
        testMap.put(i, false);
      }
    }

    System.out.println("Time with primitives : " + (System.nanoTime() - time));
  }
}
于 2013-06-21T18:49:44.503 回答