Java String、StringBuilder、StringBuffer[笔记]

String objects are string constants (unchangeable after creation), StringBuilder and StringBuffer objects are string variables (changeable). The main difference between the three is execution speed and thread safety.

execution speed

Execution speed: StringBuilder > StringBuffer > String

reason:

Changes to String objects will continuously create and recycle String objects, while StringBuilder and StringBuffer will not.

E.g:

String str = “123";
System.out.println(str);
str = str + "456";
System.out.println(str);

The JVM processes these four lines of code:

1. Create a String object and assign the value "123".

2. Print the string.

3. Create a new String object, add "456" to the value of the first object and assign it to it, and GC (garbage collection mechanism) reclaims the first object.

4. Print the new string.

thread safety

StringBuilder: Not thread safe.

StringBuffer: thread-safe (guaranteed by synchronization mechanism).

scenes to be used

String: A small number of string operations.

StringBuilder: Single-threaded bulk string manipulation.

StringBuffer: Multi-threaded bulk string operations. 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324864854&siteId=291194637