[One knowledge point per day]15-java language-string connection

Source: Internet
Author: User

Yesterday said the string concatenation, today to say connected, I mean a bunch of non-array or collection types of content to spell a string out.

The simplest is to use the + operator, and then there are StringBuilder and StringBuffer. If it is taught in training schools, it is generally said that the preferred use of StringBuilder followed by StringBuffer, do not use + inefficient. In fact, it is enough to use + in most cases, because + is actually compiled after StringBuilder (no StringBuilder version is StringBuffer), and if 2 string constants are added, they can be merged into one in the compiler.

A scenario in which you create StringBuilder manually is to use string joins in loops with many loops, similar to this:

<pre name= "code" class= "Java" >

String result = ""; for (int i = 0; i < 1_000_000; ++i) {    
In this scenario, the 4th line of code creates a new StringBuilder for Each loop execution of the For loop, which is significantly less efficient when the number of loops is greater (for example, there is an order of magnitude difference in looping 5,000 execution times on my computer). This decrease in efficiency is mainly derived from + = rather than creating StringBuilder objects, so for this:

for (int i = 0; i < 1_000_000; ++i) {    String result = xxx + yyy + zzz;}
It is not necessary to create StringBuilder manually. But when the number of loops is so great that the cost of creating objects needs to be considered, it is necessary to consider manually creating a reuse within the loop outside of the loop. But this scenario for the new person should be no chance to meet, do not care about it.


[One knowledge point per day]15-java language-string connection

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.