Talking about the difference between String, StringBuffer, StringBuilder


Preface

Understanding the design and implementation of strings and the use of related tools such as splicing is very helpful for writing high-quality code. Improper string manipulation may produce a large number of temporary strings, as well as thread safety differences. so, you must be familiar with strings to write high-quality code


1. Definition

1、String

String is a very basic and important class of the Java language, providing various basic logics for constructing and managing strings. It is a typical Immutable class, declared as a final class, and all attributes are also final. Also due to its immutability, actions like splicing and cutting strings will generate new String objects. Due to the universality of string operations, the efficiency of related operations often has a significant impact on application performance.

2、StringBuffer

StringBuffer is a class provided to solve the problem of too many intermediate objects caused by splicing mentioned above. We can use append or add methods to add strings to the end of an existing sequence or at a specified position. StringBuffer is essentially a thread-safe modifiable character sequence, which guarantees thread safety and also brings additional performance overhead, so unless thread safety is required, it is recommended to use its successor, which is StringBuilder.

3、StringBuilder

StringBuilder is a new addition in Java 1.5. There is no essential difference in capability from StringBuffer, but it removes the thread-safe part and effectively reduces overhead. It is the first choice for string splicing in most cases.

Two, String, StringBuffer, StringBuilder comparison

Class\project Initial size speed Thread safe
String null slow Safety
StringBuffer 16 slower Safety
StringBuilder 16 fast Not safe

Two, expansion

String is a typical implementation of the Immutable class. It natively guarantees basic thread safety, because you cannot modify its internal data. This convenience is even reflected in the copy constructor. Because of immutability, the Immutable object does not require extra when copying Copy the data.
Some details of StringBuffer implementation, its thread safety is achieved by adding the synchronized keyword to various methods of modifying data, which is very straightforward. In fact, this simple and rude implementation is very suitable for our common thread-safe implementations. There is no need to worry about synchronized performance. Some people say that "premature optimization is the root of all evil". Consider reliability, correctness and code availability. Readability is the most important factor in most application development.

to sum up

1 It is necessary to consider the use of the scene, if it is a code security scan, it is best to use StringBuffer.

Guess you like

Origin blog.csdn.net/aa327056812/article/details/109494072