Table of Contents
Correct usage of StringBuilder in high-performance scenarios
1. The initial length is so important that it deserves to be mentioned four times.
2. Liferay's StringBundler class
3. However, double the char[] is still wasted
4. Reuse StringBuilder
5. + and StringBuilder
6. StringBuffer and StringBuilder
7. Always hand over log string concatenation to slf4j??
Home Java javaTutorial How to use Java's StringBuilder correctly in high-performance scenarios

How to use Java's StringBuilder correctly in high-performance scenarios

May 12, 2023 pm 01:07 PM
java stringbuilder

Correct usage of StringBuilder in high-performance scenarios

About StringBuilder, most students only simply remember that you should use StringBuilder for string splicing, do not use +, and do not use StringBuffer, and then the performance will be the best. Yes, really?

Some students have also heard three specious experiences:

1. Java compiled and optimized + has the same effect as StringBuilder;

2. StringBuilder It is not thread-safe. For the sake of "safety", it is better to use StringBuffer;

3. Never splice the string of log information yourself, leave it to slf4j.

1. The initial length is so important that it deserves to be mentioned four times.

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

The default length of char[] when using new StringBuilder() is 16. Then, what should I do if I want to append the 17th character?

Use System.arraycopy to double copy and expand the capacity! ! ! !

In this way, there is the cost of array copy, and secondly, the original char[] is also wasted and will be lost by GC. As you can imagine, a 129-character string has been copied and discarded four times, 16, 32, 64, and 128, and a total of 496 characters have been applied for an array. In a high-performance scenario, this is almost unbearable.

So, how important it is to set an initial value reasonably.

But what if I really can’t estimate well? It's better to overestimate. As long as the string is larger than 16 in the end, even if it's a little wasted, it's better than doubling the capacity.

2. Liferay's StringBundler class

Liferay's StringBundler class provides another idea for length setting. It does not rush to stuff things into char[] when append(). Instead, first take a String[] and store them all, and finally add up the lengths of all Strings to construct a StringBuilder of reasonable length.

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

The waste occurs in the last step, StringBuilder.toString()

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

String's constructor will use System.arraycopy() to copy the incoming char[] To ensure security and immutability, if the story ends like this, the char[] in StringBuilder will still be sacrificed in vain.

In order not to waste these char[], one way is to use various black technologies such as Unsafe to bypass the constructor and directly assign a value to the char[] attribute of String, but few people do this.

Another more reliable method is to reuse StringBuilder. Reuse also solves the previous length setting problem, because even if the estimate is not accurate at the beginning, it will be enough after a few more expansions.

4. Reuse StringBuilder

This method comes from the BigDecimal class in the JDK (it’s okay to see how important the JDK code is). SpringSide extracts the code into StringBuilderHolder, which has only one function

public StringBuilder getStringBuilder() {
sb.setLength(0);
return sb;
}

StringBuilder.setLength() function only resets Its count pointer and char[] will continue to be reused, and toString() will also pass the current count pointer as a parameter to the String constructor, so there is no need to worry about passing in old content that exceeds the size of the new content. . It can be seen that StringBuilder is completely reusable.

In order to avoid concurrency conflicts, this Holder is generally set to ThreadLocal. For standard writing methods, see the comments of BigDecimal or StringBuilderHolder.

5. + and StringBuilder

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

The effect of this sentence after javac compilation, It is indeed equivalent to using StringBuilder, but without setting the length.

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

However, if it is like the following:

String s = “hello ”;
// separated by some other statements
s = s + user.getName();

Each statement , will generate a new StringBuilder. There are two StringBuilders here, and the performance is completely different. If s =i; is in the loop body, it will be even more ridiculous.

According to R University, the hard-working JVM engineers are in the run optimization stage. According to XX: OptimizeStringConcat (opened by default after JDK7u40), it will be possible to combine adjacent (without control statements) StringBuilder into one. Try hard to guess the length.

So, to be on the safe side, continue to use StringBuilder and set the length yourself.

6. StringBuffer and StringBuilder

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

For those students who say that StringBuffer is "safe", when have you actually seen several threads take turns appending a StringBuffer? ? ?

7. Always hand over log string concatenation to slf4j??

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

For logs that you don’t know whether to output, leaving it to slf4j to splice them only when they really need to be output can indeed save costs.

But for logs that must be output, it is faster to use StringBuilder to splice them yourself. Because looking at the implementation of slf4j, it is actually just constant indexof("{}"), constant subString(), and continuous use of StringBuilder to put it together. There is no silver bullet.

PS. The 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... and the StringBuilder is not reused.

The above is the detailed content of How to use Java's StringBuilder correctly in high-performance scenarios. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Perfect Number in Java Perfect Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

Weka in Java Weka in Java Aug 30, 2024 pm 04:28 PM

Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

Smith Number in Java Smith Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

TimeStamp to Date in Java TimeStamp to Date in Java Aug 30, 2024 pm 04:28 PM

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

How to Run Your First Spring Boot Application in Spring Tool Suite? How to Run Your First Spring Boot Application in Spring Tool Suite? Feb 07, 2025 pm 12:11 PM

Spring Boot simplifies the creation of robust, scalable, and production-ready Java applications, revolutionizing Java development. Its "convention over configuration" approach, inherent to the Spring ecosystem, minimizes manual setup, allo

See all articles