Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
170 views
in Technique[技术] by (71.8m points)

java - Which is better in terms of performance, implicit (auto) unboxing or explicit unboxing?

To put it in code - which has better performance (if there is a difference at all)?

Given this:

public class Customer
{
    ....

    public Boolean isVIP(){...}
    ...
}

Which is faster?

public void handleCustomer(Customer customer)
{
    if (customer.isVIP())  // Auto Unboxing
    {
        handleNow(customer);
    }
    else
    {  
        sayHandlingNowButQueueForTomorrow(customer);
    }
}

or this:

public void handleCustomer(Customer customer)
{
    if (customer.isVIP().booleanValue()) // Explicit unboxing
    {
        handleNow(customer);
    }
    else
    {  
        sayHandlingNowButQueueForTomorrow(customer);
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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();
    }
}

Run javap to see what it compiles to:

javap -c ImplicitTest

Here is the output:

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

}

As you can see - lines 5,6,9 (implicit) are the same as 10, 11, 14 (explicit).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...