[Java Performance] string stitching considerations

Source: Internet
Author: User

  • strings concatenation (string concatenation)

    Compiler optimizations before string answer = Integerpart + "." + mantissa;//compiler optimized string answer = new StringBuilder (Integerpart). Append (".") . Append (Mantissa). toString ();

    Because the compiler optimizes the concatenation of strings, using string concatenation in the same statement has no negative effect on performance. Just because the compiler is behind the scenes, it is not necessary to use StringBuilder instead of the "+" operator for string stitching in any scenario.

    However, when the concatenation of strings is done by multiple statements (or loops) , there is a problem:

    compiler optimization before string answer = Integerpart;answer + = "."; Answer + = mantissa;//Compiler optimized String answer = new StringBuilder (Integerpart). toString (); answer = new StringBuilder (answer) . Append ("."). ToString (); answer = new StringBuilder (answer). Append (Mantissa). ToString ();

    In code that is optimized by the compiler, the middle string object and the StringBuilder object are virtually unwanted. At this point, you can consider merging the above stitching statements into a single stitching statement. or explicitly use the StringBuilder object directly.

Summarize
    1. When string concatenation is done using a single statement, performance is equivalent to using StringBuilder.
    2. Consider merging these statements or explicitly using StringBuilder when you are using multiple statements to complete string stitching.

[Java Performance] string stitching considerations

Related Article

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.