Concatenates multiple strings, causing comparison between strings and stringBuilder.

Source: Internet
Author: User
There are two methods to connect multiple strings: using the String-type overload +And use the StringBuilder class.

For example, the String-type overload+Operator string str1 = "two ";
String str2 = "one" + str1 + "three ";

Example: Use StringBuilder class StringBuilder _ str = new StringBuilder ();
String str = "Perfect ";
_ Str. Append ("");
_ Str. Append (str );
_ Str. Append ("Day ");

The String object concatenation operation always creates new objects with existing strings and new data. The StringBuilder object maintains a buffer to accommodate the concatenation of new data. If there is enough space, new data will be appended to the end of the buffer; otherwise, a new and larger buffer will be allocated, and the data in the original buffer will be copied to the new buffer, then, append the new data to the new buffer.

The performance of string or stringbuilder object concatenation operations depends on the memory allocation frequency. The String concatenation operation allocates memory each time, while the stringbuilder concatenation operation allocates memory only when the stringbuilder object buffer is too small to accommodate new data. Therefore, if you concatenate a fixed number of string objects, the string class is more suitable for concatenation. In this case, the compiler may even combine the concatenation operations into one operation. If you concatenate any number of strings, The stringbuilder object is more suitable for concatenation. For example, a loop concatenates any number of strings entered by the user.

For stringbuilder and string performance and when to use, see: http://www.codeproject.com/useritems/StringBuilder_vs_String.asp

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.