In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly explains how to use StringBuilder in high-performance scenarios. Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Let's let Xiaobian take you to learn how to use StringBuilder in high-performance scenes!
1. The initial length is so important, it's worth saying four times.
StringBuilder has a char[] inside, and the continuous append() is the process of continuously filling things into char[].
The default length of char[] when new StringBuilder() is 16, then what if you want to append the 17th character?
Use System.arraycopy to multiply and expand!!!
The cost of copying the array is thus incurred, and the original char[] is wasted to be GC dropped. As you can imagine, a string of 129 characters, after 16, 32, 64, 128 copies and discarding four times, a total of 496 characters of the array, in high-performance scenarios, this is almost unbearable.
Therefore, it is important to set an initial value reasonably.
But what if I'm really wrong? A little bit more is fine, as long as the string ends up larger than 16, even if it is wasted a little, it is better than multiplying the expansion.
2. StringBundler class of Liferay
Liferay's StringBundler class provides another idea for length settings. It doesn't rush to stuff char[] when append(), but first takes a String[] and stores them all. Finally, it adds up the lengths of all Strings to construct a StringBuilder of reasonable length.
3. But it was a waste of double char[].
Waste occurs at the last step, StringBuilder.toString()
// Create a copy, don't share the array
return new String(value, 0, count);
String's constructor makes a copy of the char[] passed in with System.arraycopy() to ensure security immutability, and if the story ends like this, char[] in StringBuilder is sacrificed for nothing.
One way to avoid wasting char[] is to bypass constructors and assign char[] properties to String directly, using various black technologies such as Unsafe, but few people do this.
Another reliable way is to reuse StringBuilder. Reuse also solves the previous length setting problem, because even if the initial estimation is not accurate, it is enough after several expansions.
4. Reuse StringBuilder
This practice comes from the BigDecimal class in JDK (nothing to see how important JDK code is), SpringSide extracts the code into StringBuilderHolder, which has only one function
public StringBuilder getStringBuilder() {
sb.setLength(0);
return sb;
}
StringBuilder.setLength() resets only its count pointer, char[] continues to be reused, and toString() passes the current count pointer as an argument to the String constructor, so don't worry about passing in old content that exceeds the size of the new content. StringBuilder is completely reusable.
To avoid concurrency conflicts, this Holder is generally set to ThreadLocal, standard writing see BigDecimal or StringBuilderHolder comments.
5. + StringBuilder
String s = "hello " + user.getName();
The javac-compiled effect of this sentence is indeed equivalent to using StringBuilder, but without setting the length.
String s = new StringBuilder().append("hello").append(user.getName());
However, if something like this:
String s = "hello ";
//separated by other statements
s = s + user.getName();
Each statement generates a new StringBuilder, so there are two StringBuilders, and the performance is completely different. If s+=i; is in the loop body, it's even more ridiculous.
According to R, the hard JVM engineers in the optimization stage, according to +XX:+OptimizeStringConcat(JDK7u40 after the default open), the adjacent (not separated by control statements) StringBuilder synthesis of one, will also try to guess the length.
So, to be safe, continue to use StringBuilder and set the length.
6. StringBuffer and StringBuilder
StringBuffer and StringBuilder are inherited from AbstractStringBuilder, the only difference is that StringBuffer functions have synchronized keywords.
For those of you who say StringBuffer is "safe," when have you ever seen several threads take turns appending a StringBuffer???
7. Always hand over the string concatenation of logs to slf4j??
logger.info("Hello {}", user.getName());
For logs that don't know whether to output or not, it's really cost-effective to leave them to slf4j to splice when they really need to be output.
But for logs that must be output, it is faster to use StringBuilder to splice them directly. Because look at the implementation of slf4j, in fact, it is constantly indexof("{}"), constantly subString(), and then constantly put together with StringBuilder, no silver bullet.
PS. StringBuilder in slf4j reserves 50 characters outside the original Message. If the variable parameters add up to more than 50 characters, they still have to be copied and expanded... StringBuilder is not reused either.
At this point, I believe everyone has a deeper understanding of "how to use StringBuilder in high-performance scenarios," so let's actually operate it! Here is the website, more related content can enter the relevant channels for inquiry, pay attention to us, continue to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.