Comparison of String, StringBuilder, StringBuffer in Java
"TLDR: This article compares the three string classes in Java: String, StringBuilder, and StringBuffer, and points out their differences in performance and thread safety. String is immutable, and frequent modifications are inefficient; StringBuilder is thread-safe, but inefficient; StringBuffer is both thread-safe and efficient, but requires locking. Finally, the article also mentions the performance issues of string concatenation in Golang and its comparison with Java."
String
In Java, String is an immutable class (declared as final class). Any operation on String will create a new String object, whose storage address is in the string constant pool.
The advantage of this is thread safety. When different threads modify the same string, a new String will be created; the disadvantage is that the efficiency is low when the string is frequently modified.
StringBuilder
In the case of frequent additions, deletions and modifications to strings, the efficiency of String is low. At this time, the StringBuilder class (with built-in append and add methods) was added to Java, which can modify strings in place. It is very efficient, but it also brings thread insecurity issues.
StringBuffer
There is not much difference between StringBuffer and StringBuilder, except that the synchronized synchronization keyword is added to each operation method, so it is a thread-safe and modifiable character sequence.
Summary
-
Performance
-
Thread safe (with lock) - slow
-
Thread-unsafe (no locks) - fast
-
-Usage scenarios
-
Small number of operations —
String -
Single-threaded bulk operations —
StringBuilder -
Multi-threaded bulk operations —
StringBuffer
-
golang comparison supplement:
-
I was learning golang recently and also encountered the performance problem of String splicing. Like Java, Golang's String is immutable, and frequent use will create a large number of intermediate strings. Golang provides two processing methods, strings.Builder and Bytes.Buffer. The bottom layer of both methods maintains a dynamically variable
[]bytesarray. strings.builder will be slightly faster than bytes.Buffer, because strings.builder directly converts the[]bytesdynamic array into a string, while bytes.Buffer will re-apply a space to store the converted final string. -
Bytes.Buffer in Golang is different from StringBuffer in Java and is not locked.
-