Concatenation of strings with Stringbuffer/stringbuilder

Source: Internet
Author: User
Error Case

The heavy use of string concatenation in loops can result in unnecessary memory consumption and frequent garbage collection. Error Analysis

Wrong wording:

String str = "";
for (int i = 0; i < 1000 i++) {
    str = "" + i;
}
System.out.println (str);

can use "+" or "+ +" operator stitching a large number of strings, in a large number of string concatenation operation, the direct addition of two string objects, will allocate memory for the newly created string, the original two string objects are not released, which consumes a lot of memory resources.

In our highly visited web site, some of the small problems may be magnified, which can seriously affect the performance of the system bottlenecks. correct usage

StringBuffer buf = new StringBuffer ();
for (int i = 0; i < 1000 i++) {
    buf.append (""). Append (i);
}
String str = buf.tostring ();
System.out.println (str);
test the attention point

The growth of memory footprint through continuous stress testing

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.