Stringbuffer and optimization of Stringbuilder String

string

Speaking of the last string is best derived from a character type, the principle is realized by a char [] . We know that can not be changed once created an array, so every time a string splicing is carried out in the new add a new string, so to consume memory greatly in jdk1.0 began to appear stringbuffer optimization and create objects in the form of heap memory is stored in so in order to ensure the safety of stringbuffer add a lot of weight lock (synchronize) due to lock led his efficiency is not too high , after jdk1.5 and the birth of a new string optimization stringbuilder canceled a lot of weight lock (synchronize) to improve the efficiency but led to a thread-safe . Look at the situation using

stringbuffer

jdk1.0 born stringbuffer, it is splicing the string of small memory consumption, provide internal append () method. When the data reaches a certain amount will trigger expansion. The initial capacity of each expansion 16 * 2 + 2 will length . There may be someone asked why 2 plus, because if the initial capacity is set to 0 not always 0 2 plus the initial capacity is set. Splicing process is performed each time both the weight of the string lock (Synchronize) so that the efficiency is relatively low

stringbuilder

jdk1.5 birth stringbuilder, he and stringbuffer of operation is the same but later reduced the weight of the lock 's efficiency is improved but it also leads to unsafe thread to see business needs choose to use buffer or builder.

Guess you like

Origin www.cnblogs.com/wanghaozi/p/11577021.html