Summary of StringBuilder's high-performance usage in Java

Source: Internet
Author: User

Summary of StringBuilder's high-performance usage in Java

For StringBuilder, you can simply remember that String concatenation must use StringBuilder, not ++, or StringBuffer, and the performance is the best. Is it true?

Some of you have heard of three similar experiences:

1. After Java compilation is optimized, + the effect is the same as that of StringBuilder;

2. StringBuilder is NOT thread-safe. For the sake of "security", it is best to use StringBuffer;

3. Never splice the log information string with slf4j.

1. The initial length is important and it is worth mentioning four times.

There is a char [] In StringBuilder, and the constant append () is the process of constantly filling in the char.

When new StringBuilder () is used, the default length of char [] is 16. What should I do if I want to append 17th characters?

Use System. arraycopy to multiply the capacity !!!!

In this way, the cost of copying an array is reduced, and the original char [] is wasted for GC. It can be imagined that a 129-character string, after four times of copying and discarding 16, 32, and 64,128, has applied for a 496-character array. In high-performance scenarios, this is almost intolerable.

Therefore, setting an initial value is important.

But what if I really cannot estimate it? It is better to estimate a little more, as long as the character string is greater than 16 at the end, even if a little bit is wasted, it is better than doubling the expansion.

2. StringBundler class of Liferay

The StringBundler class of Liferay provides another idea of setting the length. It does not rush to put stuff into char [] During append, instead, we first store a String [] and add the length of all strings to construct a StringBuilder with a reasonable length.

3. However, double the char [] is still wasted.

Waste occurs in the last step, StringBuilder. toString ()

 
 
  1. // Create a copy, don't share the array 
  2. return new String(value, 0, count); 

The String constructor uses System. arraycopy () copies an input char [] to ensure the security of non-variability. If the story ends like this, the char [] In StringBuilder will still be sacrificed in vain.

To avoid wasting these char [], one method is to use various black technologies such as Unsafe to directly assign values to the char [] and count attributes of String without passing through the constructor, but few do.

Another reliable method is to reuse StringBuilder. The reuse also solves the problem of length settings, because even if the estimation is inaccurate at the beginning, it is enough to expand the capacity several times later.

4. Reuse StringBuilder

This method comes from the BigDecimal class in JDK. It's okay to check how important JDK code is.) In SpringSide, code is extracted into StringBuilderHolder, which has only one function.

 
 
  1. public StringBuilder getStringBuilder() { 
  2.      sb.setLength(0); 
  3.      return sb; 

StringBuilder. the setLength () function only resets its count pointer, while char [] continues to be reused, while toString () when the previous count pointer is passed as a parameter to the String constructor, you do not have to worry about transmitting the old content that exceeds the size of the new content. It can be seen that StringBuilder is completely reusable.

To avoid concurrency conflicts, this Holder is generally set to ThreadLocal. For the standard syntax, see the comments of BigDecimal or StringBuilderHolder.

5. + and StringBuilder

 
 
  1. String s = “hello ” + user.getName(); 

The effect of this sentence after javac compilation is indeed equivalent to using StringBuilder, but the length is not set.

String s = new StringBuilder (). append ("hello"). append (user. getName ());

However, if:

 
 
  1. String s = "hello ";
  2. // Some other statements are separated
  3. S = s + user. getName ();

Each statement generates a new StringBuilder. Here there are two StringBuilder, and the performance is completely different. If it is in the loop body s + = I; it is more than nothing.

According to R, hard-working JVM engineers put the adjacent (not separated by control statements in the middle) in the optimization stage according to + XX: + OptimizeStringConcat (which is enabled by default after JDK7u40) stringBuilder combines a string and tries to guess the length.

Therefore, we should continue to use StringBuilder and set the length.

6. StringBuffer and StringBuilder

Both StringBuffer and StringBuilder inherit from AbstractStringBuilder. The only difference is that all StringBuffer functions have the synchronized keyword.

For those who say that StringBuffer is "safe", when have you actually seen several threads rotating append a StringBuffer ???

7. Always splice the log string to slf4j ??

 
 
  1. logger.info("Hello {}", user.getName()); 

For logs that do not know whether to output or not, it can be spliced to slf4j only when the output is really required to save costs.

However, for logs that must be output, it is faster to directly splice them with StringBuilder. Because the implementation of slf4j is actually the constant indexof ("{}"), the constant subString (), and the constant use of StringBuilder. There is no silver bullet.

The StringBuilder in PS. slf4j reserves 50 characters out of the original Message. If the variable parameters add up to 50 characters long, you must copy and scale up ...... In addition, StringBuilder is not reused.

8. Summary

StringBuilder concatenates strings of 129 characters by default, and applies for an array of 625 characters. Therefore, in high-performance scenarios, a ThreadLocal reusable StringBuilder should always be considered. After reuse, you no longer need to play the game with the length of guesses.

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.