stringbuffer analysis differs stringbuilder

They are in the end what difference does it!

 

Three are used to manipulate strings, String typically used to define a variable, and is usually used to StringBuilder StringBuffer string splicing operation. But in fact the same String can be used to concatenate strings, how can we use it rarely, so talking about is the bottom three.

 

 

String underlying code is a modified final use char array, which means that after a String variable is defined, the content of the variable is immutable.

 

StringBuilder and StringBuffer are inherited from AbstractStringBuilder, char array class is not modified with final, the content is variable, this is what this means.

such as:

String s1= "a";

String s2 = new String("b") ;

String s3 = s1+s2;

If so, we get "ab" string, not because the underlying string String can not be changed, it will create three objects will take up memory, but none of these three objects has been lost references, so can not jvm garbage collection, resulting in substantial waste of memory resources, which is not respected in our development, and StringBuilder and StringBuffer such a problem does not exist.

 

We can see through the underlying code in splicing StringBuilder with StringBuffer string, the string length is determined by whether or not enough to create a new array to encapsulate the data, and the original object is abandoned references for garbage collection, thereby reducing memory waste, so when string concatenation and other operations, we usually use the StringBuilder with StringBuffer, but both have different efficiency in the implementation of high efficiency StringBuilder, which is why?

By the underlying source code can be found at StringBuffer string concatenation, using the synchronization lock, the security is improved, and the synchronization lock StringBuilder is not used, so that efficiency is improved.

Guess you like

Origin www.cnblogs.com/zhengcheng-java/p/11432438.html