Summary of StringBuilder in Java in high performance usage

Source: Internet
Author: User

About StringBuilder, the general students simply remember, string splicing to use StringBuilder, do not use +, do not use StringBuffer, and then the performance is the best, really?

There are also some students who have heard three plausible experiences:

1. Java compilation after optimization + and StringBuilder the same effect;

2. StringBuilder is not thread-safe, it is best to use stringbuffer for the sake of "safety";

3. Never make a string of log messages yourself, and give it to slf4j.

1. The initial length is very important, it is worth saying four times.

StringBuilder's interior has a char[], and constant append () is the process of filling things up in char[].

The default length of char[] when new StringBuilder () is 16, and then, what if you want to append 17th character?

With system.arraycopy multiply replication expansion!!!!

In this way there is the cost of the array copy, and the original char[] also wasted to be GC off. As you can imagine, a 129-character string, after 16,32,64, 1284 copies and discards, applies a total of 496-character arrays, which is hardly tolerated in high-performance scenarios.

Therefore, it is more important to set a reasonable initial value.

But what if I'm not really good at estimating it? A little more than a bit better, as long as the string at the end of more than 16, even a little wasted, but also more than the multiplication of good.

2. Liferay's Stringbundler class

Liferay's Stringbundler class provides another way to set the length of the append (), when it is not in the rush to the char[], but first take a string[] to save them all, In the end, the length of all strings is added to construct a reasonable length of StringBuilder.

3. But it's a waste of char[]

Waste takes place in the final step, stringbuilder.tostring ()

Create a copy, don ' t share the Arrayreturn new String (value, 0, count);

The constructor of string uses System.arraycopy () to copy an incoming char[] to ensure that security is immutable, and if the story ends this way, StringBuilder's char[] is sacrificed in vain.

In order not to waste these char[], one way is to use a variety of black technology such as unsafe, bypassing the constructor directly to the string char[] and the Count property, but few people do so.

Another way to do this is to reuse StringBuilder. and reuse, but also solves the previous length setting problem, because even if the initial estimate is not allowed, more than a few times after the expansion is enough.

4. Reusing StringBuilder

This approach comes from the BigDecimal class in the JDK (it's okay to see how important the JDK code is), and the Springside extracts the code into Stringbuilderholder, with only one function

Public StringBuilder Getstringbuilder () {     sb.setlength (0);     return SB;}

The Stringbuilder.setlength () function resets only its count pointer, while char[] continues to be reused, and ToString () passes the current count pointer as a parameter to the constructor of string. So don't worry about passing on old content that's bigger than the new content size. It can be seen that StringBuilder is completely reusable.

To avoid concurrency conflicts, this holder is generally set to ThreadLocal, and the standard notation is shown in BigDecimal or Stringbuilderholder annotations.

5. + and StringBuilder
String s = "Hello" + user.getname ();

This sentence after the Javac compiled effect, is indeed equivalent to the use of StringBuilder, but not set the length.

String s = new StringBuilder (). Append ("Hello"). Append (User.getname ());

However, if you like:

String s = "Hello";//separated by some other statements s = S + user.getname ();

Each statement generates a new StringBuilder, where there are two StringBuilder, and the performance is completely different. If it is s+=i in the circulation body; There is much more to flaky.

According to R Big, the effort of the JVM engineers in the Run optimization phase, according to +xx:+optimizestringconcat (jdk7u40 after the default open), the adjacent (the middle is not separated from the control statement) StringBuilder to synthesize one, will also try to guess the length.

So, for the sake of insurance, continue to use StringBuilder and set the length of the good.

6. StringBuffer and StringBuilder

StringBuffer and StringBuilder are inherited from Abstractstringbuilder, the only difference is that stringbuffer functions have synchronized keywords.

Those who say StringBuffer "safe" classmate, actually when you saw several threads take turns append a stringbuffer situation???

7. Always send the string of logs to slf4j??
Logger.info ("Hello {}", User.getname ());

For those who do not know the output of the log, to slf4j in the real need to output when the splicing does save cost.

But for a certain to output the log, direct their own StringBuilder stitching faster. Because look at the realization of slf4j, in fact is constantly indexof ("{}"), constantly substring (), and then continue to use the StringBuilder together, no silver bullets.

The StringBuilder in PS. SLF4J has 50 characters reserved outside of the original message, and if the variable parameter is added up to 50 characters long, it has to be duplicated. And StringBuilder is not reused.

8. Summary

StringBuilder default notation, will be 129-length string concatenation, a total of 625-character array request. So in high-performance scenarios, always consider a threadlocal reusable StringBuilder. And after reuse, you don't have to play the game of guessing length.

Summary of StringBuilder in Java in high performance usage

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.