我看到了以下代码,并想知道编码器的意图。这是自动装箱的相关性能吗?
map.put("doesntMatter", Boolean.TRUE);
他本可以做到:
map.put("doesntMatter", true);
第一次做的好处是什么?
答案 0 :(得分:4)
我写了一个例子:
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编译器就会完成它的工作并对其进行优化。
答案 1 :(得分: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));
}
}
答案 2 :(得分:0)
来自源代码 -
public static final Boolean TRUE = new Boolean(true);
public Boolean(boolean value) {
this.value = value;
}
private final boolean value;
正如您所看到的,TRUE
调用仅设置值的构造函数。所以理论上它的效率稍差,因为它做了一些额外的工作来获得相同的结果。