search
HomeJavajavaTutorialDistinguish the String, StringBuffer and StringBuilder string classes in Java

1 String
String: String constant, the length of the string is immutable.

2 StringBuffer
StringBuffer: String variable (Synchronized, that is, thread-safe). If you want to frequently modify the string content, it is best to use StringBuffer for efficiency reasons. If you want to convert it to String type, you can call the toString() method of StringBuffer.
Java.lang.StringBuffer Thread-safe mutable character sequence. At any point in time it contains a specific sequence of characters, but the length and content of that sequence can be changed through certain method calls. String buffers can be used safely by multiple threads.
The main operations on StringBuffer are the append and insert methods, which can be overloaded to accept any type of data. Each method effectively converts specified data into a string and then appends or inserts the characters of that string into a string buffer. The append method always adds these characters to the end of the buffer; the insert method adds characters at a specified point. For example, if z refers to a string buffer object whose current content is "start", then this method call z.append("le") will cause the string buffer to contain "startle", while z.insert(4, " le") will change the string buffer to contain "starlet".

3 StringBuilder
StringBuilder: String variable (non-thread-safe).
java.lang.StringBuilder is a variable character sequence, which is new in JDK5.0. This class provides a StringBuffer-compatible API but does not guarantee synchronization. This class is designed as a drop-in replacement for StringBuffer when the string buffer is used by a single thread (which is a common situation). It is recommended to prefer this class if possible, as it is faster than StringBuffer in most implementations. The methods for both are basically the same.
In most cases, StringBuilder > StringBuffer.

4 Differences between the three
The main performance difference between the String type and StringBuffer: String is an immutable object, so every time the String type is changed, a new String object will be generated, and then Point the pointer to a new String object, so it is best not to use String for strings that frequently change content, because every time an object is generated, it will have an impact on system performance. Especially when there are too many unreferenced objects in the memory, the JVM's GC will As soon as it starts working, performance degrades.
When using the StringBuffer class, the StringBuffer object itself will be operated every time instead of generating a new object and changing the object reference. Therefore, it is recommended to use StringBuffer in most cases, especially when string objects change frequently.
In some special cases, the string concatenation of String objects is actually interpreted by the JVM as the concatenation of StringBuffer objects, so in these cases the speed of String objects is not slower than that of StringBuffer objects, for example:

String S1 = “This is only a” + “ simple” + “ test”;
StringBuffer Sb = new StringBuilder(“This is only a”).append(“ simple”).append(“ test”);

The speed of generating String S1 objects is not slower than StringBuffer. In fact, in the JVM, the following conversion is automatically done:

String S1 = “This is only a” + “ simple” + “test”;

The JVM directly treats the above statement as:

String S1 = “This is only a simple test”;

, so it is very fast. But it should be noted that if the spliced ​​string comes from another String object, the JVM will not automatically convert it, and the speed will not be that fast. For example:

String S2 = “This is only a”;
String S3 = “ simple”;
String S4 = “ test”;
String S1 = S2 +S3 + S4;

This Sometimes, the JVM will behave in the original way.
In most cases, StringBuffer > String.

4.StringBuffer and StringBuilder
There is almost no difference between them. They are basically calling various methods of the parent class. An important difference is that StringBuffer is thread-safe, and most of the internal methods are preceded by Keyword synchronized, this will consume a certain amount of performance. StringBuilder is not thread-safe, so it is more efficient.

public static void main(String[] args) throws Exception {
    String string = "0";
    int n = 10000;
    long begin = System.currentTimeMillis();
    for (int i = 1; i < n; i++) {
      string += i;
    }
    long end = System.currentTimeMillis();
    long between = end - begin;
    System.out.println("使用String类耗时:" + between+"ms");
  
    int n1 = 10000;
    StringBuffer sb = new StringBuffer("0");
    long begin1 = System.currentTimeMillis();
    for (int j = 1; j < n1; j++) {
      sb.append(j);
    }
    long end1 = System.currentTimeMillis();
    long between1 = end1 - begin1;
    System.out.println("使用StringBuffer类耗时:" + between1+"ms");
  
    int n2 = 10000;
    StringBuilder sb2 = new StringBuilder("0");
    long begin2 = System.currentTimeMillis();
    for (int k = 1; k < n2; k++) {
      sb2.append(k);
    }
    long end2 = System.currentTimeMillis();
    long between2 = end2 - begin2;
    System.out.println("使用StringBuilder类耗时:" + between2+"ms");
  }

Output:

使用String类耗时:982ms
使用StringBuffer类耗时:2ms
使用StringBuilder类耗时:1ms

Although this number is different every time it is executed, and the situation of each machine It's not the same, but a few things are certain. The String class consumes significantly more than the other two. Another point is that StringBuffer consumes more than StringBuilder, although the difference is not obvious.


5 Usage strategy
(1) Basic principles: If you want to operate a small amount of data, use String; if you want to operate a large amount of data with a single thread, use StringBuilder; if you want to operate a large amount of data with multiple threads, use StringBuffer.
(2) Do not use the "+" of the String class for frequent splicing, because the performance is extremely poor. You should use the StringBuffer or StringBuilder class. This is an important principle in Java optimization. For example: when using String, use "+" to form a temporary StringBuffer object on the JVM when splicing strings. At the same time, an object is created on each string. To splice two strings, a total of 4 need to be created. Object! (A String to save the result, two string objects, and a temporary StringBuffer object). When using StringBuffer, you only need to create 2 objects! A StringBuffer object and the String object that holds the final result.
(3) In order to obtain better performance, the capacity of StirngBuffer or StirngBuilder should be specified as much as possible when constructing it. Of course, this is not necessary if the length of the string you are operating does not exceed 16 characters. Not specifying capacity can significantly reduce performance.
(4) StringBuilder is generally used inside methods to complete functions similar to "+". Since it is thread-unsafe, it can be discarded after use. StringBuffer is mainly used in global variables.
(5) Compared with using StringBuffer, using StirngBuilder can only achieve a performance improvement of about 10% to 15% under the same circumstances, but it will run the risk of multi-threading insecurity. In actual modular programming, the programmer responsible for a certain module may not necessarily be able to clearly judge whether the module will be run in a multi-threaded environment. Therefore: unless it is determined that the bottleneck of the system is on StringBuffer, and you are sure that StringBuilder can be used only if the module does not run in multi-threaded mode; otherwise, StringBuffer is still used.

For more articles on the analysis of String, StringBuffer and StringBuilder string classes in Java, please pay attention to the PHP Chinese website!

Statement
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
How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to elegantly obtain entity class variable names to build database query conditions?How to elegantly obtain entity class variable names to build database query conditions?Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How to use the Redis cache solution to efficiently realize the requirements of product ranking list?How to use the Redis cache solution to efficiently realize the requirements of product ranking list?Apr 19, 2025 pm 11:36 PM

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

How to safely convert Java objects to arrays?How to safely convert Java objects to arrays?Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

How do I convert names to numbers to implement sorting and maintain consistency in groups?How do I convert names to numbers to implement sorting and maintain consistency in groups?Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to set the default run configuration list of SpringBoot projects in Idea for team members to share?How to set the default run configuration list of SpringBoot projects in Idea for team members to share?Apr 19, 2025 pm 11:24 PM

How to set the SpringBoot project default run configuration list in Idea using IntelliJ...

See all articles

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.