Beware of the "honey" traps in the Java compiler

Source: Internet
Author: User

First, preface

As the Java compiler continues to evolve, it provides programmers with more and more "Honey" (Compiler Suger), which greatly facilitates the development of programs, such as the enhanced mode of foreach, automatic unboxing and boxing, and string connection operations ...

These "honey" bring us a lot of convenience, but there are also some pitfalls.

Second, automatic packing traps

First of all, let's take a look at the most familiar automatic disassembly box (boxing), boxing can automatically help us to complete the basic type and basic type of wrapper between the conversion.

Refer to the famous Java Gossip (http://openhome.cc/Gossip/Java/Wrapper.html) for specific use.

Of course, there are some notorious traps for this honey. For these traps, we can also get alerts from Java Gossip (http://openhome.cc/Gossip/Java/AutoBoxUnBox.html).

Third, string connection trap

Here we will focus on an easy to ignore the trap "string connection", with the following two tostring method, which would you choose?

Snippet A:

Public String toString () {    return "{a:" + A + ", B:" + B + ", C:" + C + "}";}

Snippet B:

Public String toString () {    StringBuilder sb = new StringBuilder (+);    Return Sb.append ("{A:"). Append (a).          append (", B:"). Append (b). Append          (", C:"). Append (c)          . Append ("}")          . toString ();}

Remember that some books have said that we should use StringBuilder when we do large-scale string connections, because StringBuilder can avoid repeatedly creating string objects.

This advice may be right before JDK6, but it is not the case after JDK6. We use the Anti-compilation tool to see how snippet a will be optimized by the Java compiler.

Snippet C:

Public String toString ()    {        return (new StringBuilder ()). Append ("{a:"). Append (a). Append (", B:"). Append (b). Append (", C:"). Append (c). Append ("}"). toString ();    

Snippet C is the result of the Java compiler optimization Snippet A, we can see that the Java compiler has converted the string "+" operator connection to the StringBuilder append connection.

Moreover, Snippet A is more concise and more convenient than Snippet B. So are we going to give up the StringBuilder when we write the code?

Below, let's compare two ToString code snippets:

Snippet D:

    Public String toString ()    {        string str = "";        for (int i=0;i<100000;i++) {            str + = "*";        }        return str;    }

Snippet E:

    Public String toString ()    {        StringBuilder strbuilder = new StringBuilder ();        for (int i=0;i<100000;i++) {            strbuilder.append ("*");          }        return strbuilder.tostring ();        }

So, will the performance of Snippnet D and snippet E be the same?

A simple test will show that the performance gap between the two is large,

Snippet D takes about 12s, but Snippet E is less than 1ms.

We can still find the answer through the Anti-compilation tool, and we can find that snippet D is compiled into the following fragment:

    Public String toString ()    {        string s = "";        for (int i = 0; i < 0x186a0; i++)            s = (new StringBuilder ()). Append (s). Append ("*"). toString ();        s = (new StringBuilder ()). Append (s). Append ("*"). toString ();        return s;    }

That is, the Java compiler does not optimize the for-loop structure, and it continues to create StringBuilder objects and string objects repeatedly.

Therefore, when we choose to do a lot of string connection operations in a for struct, we still use StringBuilder's append operation.

Iv. Summary

The Java compiler gives us a lot of honey and offers many optimizations (many JMM based optimizations will bring us more "surprise", such as order reordering).

These optimizations give us convenience and performance improvements, but while we use them, we must also understand the rationale behind these optimizations. Otherwise, you may have to live in the "surprise".

Beware of the "honey" traps in the Java compiler

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.