String and StringBu ff er, what's the difference StringBuilder is? Why String is immutable?

Variability in
simple terms:
String class using fi nal key character array stored string, private final char value [], so the String object is immutable.
The StringBuilder and StringBu ff er inherit from AbstractStringBuilder class, but also use char string array of characters stored in AbstractStringBuilder in [] value but not modified by the fi nal keywords, so the two objects are variable.
And StringBuilder constructor StringBu ff er are calling the parent class constructor is implemented AbstractStringBuilder

Source:

abstract class AbstractStringBuilder implements Appendable, CharSequence {    
	char[] value;    
	int count;    
	AbstractStringBuilder() {    }    
	AbstractStringBuilder(int capacity) {        
	value = new char[capacity];    
}
AbstractStringBuilder.java

Thread safety
in String objects are immutable, it can be understood as a constant thread safe. AbstractStringBuilder is StringBuilder StringBu ff er with the common parent class that defines the basic operation of some of the string, such as expandCapacity, append, insert, indexOf other public methods.
StringBu ff er method adds genlock or method call added a synchronization lock, so are thread-safe.
StringBuilder and no method plus genlock, so not thread-safe.

performance

Every time a change of type String, generates a new String object, then the pointer to the new String object.
StringBu ff er each time to StringBu ff er object itself to operate, instead of generating new object and change the object reference.
Use StirngBuilder compared to the use StringBu ff er only get about 10% to 15% performance increase under the same circumstances, but they bear the risk of multithreading unsafe.

For use of three summary:
1. The operation of a small amount of data String =
2. large amount of data in a single-threaded operating the operating string buffer large amounts of data operation at the StringBuilder = 3. 3. A multi-threaded operating string buffer = StringBu ff er

Published 53 original articles · won praise 5 · Views 450

Guess you like

Origin blog.csdn.net/qq_45287265/article/details/104967295