Java, String, StringBuffer, StringBuilder difference

String class is used to represent those created after the string will not be changed, it is immutable 's.

StringBuffer class is used to represent the contents of a variable string, and provide a method of modifying the underlying string. String buffer may be safely used in a plurality of threads . It may be necessary when these methods are synchronized so that all operations on any specific example is if the serial order of occurrence, and the method sequentially calls directed to each thread sequentially consistent. When we splicing character, use the StringBuffer class instead of the String class, because the former than the latter hundred times faster.

StringBuilder class is designed as StringBuffera drop-in replacement, used in a string buffer is a single thread when in use (which is common). If possible, we recommend the use of such priority, because in most implementations, it is more than StringBufferfast to.

Example:

String str = "You are nice. "; Str + = "I love you so much."; If it StringBuffer class, as follows:

StringBuffer str = new StringBuffer ( "You are nice."); Str.append ( "I love you so much."); From the face of only one class String plus sign (+) completes the string concatenation, The class has to call a StringBuffer append () method, whether or not to implement a simpler, more pure it? In fact, let's look at the internal program run what's happening:  through the program bytecode compiler (bytecode) demonstrated the essence: when splicing directly with the String class object, JVM will create a temporary StringBuffer class object, and call its append () method to complete the string concatenation, since the string class is immutable, the splicing operation has to use StringBuffer class (and will --JVM "you are nice." and "I love you so much . "create two new String object). After that, the temporary StringBuffer object and then transition to a String, costly! Seen in this a simple one splicing process, we let the program creates four objects: two to be spliced String, a temporary StringBuffer, StringBuffer and finally transformed into a String-- it is certainly not the original str, the reference name has not changed, but it points to a new String object. And if you use direct StringBuffer class, the program will produce only two objects: String and StringBuffer when the initial splicing ( "I love you so much.  " ), And no longer need to create a temporary StringBuffer class object and then have to convert it back to a String object. Imagine, when we strings to be recycled several segments spliced with the String class direct action will bring the number of additional overhead, how much useless temporary StringBuffer object generation, and how many times unnecessary processing of which casts.






Reproduced in: https: //www.cnblogs.com/moiyer/archive/2011/11/24/2316152.html

Guess you like

Origin blog.csdn.net/weixin_33692284/article/details/94693179