哪个在性能,隐式(自动)拆箱或显式拆箱方面更好?
问题描述:
把它放在代码中 - 性能更好(如果有差异的话)?
To put it in code - which has better performance (if there is a difference at all)?
鉴于此:
public class Customer
{
....
public Boolean isVIP(){...}
...
}
哪个更快?
public void handleCustomer(Customer customer)
{
if (customer.isVIP()) // Auto Unboxing
{
handleNow(customer);
}
else
{
sayHandlingNowButQueueForTomorrow(customer);
}
}
或者:
public void handleCustomer(Customer customer)
{
if (customer.isVIP().booleanValue()) // Explicit unboxing
{
handleNow(customer);
}
else
{
sayHandlingNowButQueueForTomorrow(customer);
}
}
答
否它们之间的区别,你可以在字节码中验证它:
No difference between them, you can verify it in the bytecode:
public class ImplicitTest {
public static void main(String[] args) {
Boolean b = true;
boolean i = b;
boolean e = b.booleanValue();
}
}
运行 javap
看看它是什么编译为:
Run javap
to see what it compiles to:
javap -c ImplicitTest
以下是输出:
Compiled from "ImplicitTest.java"
public class ImplicitTest extends java.lang.Object{
public ImplicitTest();
Code:
0: aload_0
1: invokespecial #1; //Method java/lang/Object."<init>":()V
4: return
public static void main(java.lang.String[]);
Code:
0: iconst_1
1: invokestatic #2; //Method java/lang/Boolean.valueOf:(Z)Ljava/lang/Boolean;
4: astore_1
5: aload_1
6: invokevirtual #3; //Method java/lang/Boolean.booleanValue:()Z
9: istore_2
10: aload_1
11: invokevirtual #3; //Method java/lang/Boolean.booleanValue:()Z
14: istore_3
15: return
}
如您所见 - 第5,6,9行(隐式)与10,11,14(显式)相同。
As you can see - lines 5,6,9 (implicit) are the same as 10, 11, 14 (explicit).