String StringBuffer StringBuilder differences

Source: Internet
Author: User
string literal constant
StringBuffer string variable (thread safe)
StringBuilder string variable (non-thread safe)
Briefly, the main performance difference between the string type and the StringBuffer type is that the string is an immutable object, so each time a change is made to the string type it is equivalent to generating a new string object and then pointing the pointer to the new Strin G object, so it is best not to use a string to change the content, because each generation of the object will have an impact on the system performance, especially when there is no reference object in memory, the JVM's GC will start to work, the speed will be quite slow.
If you use the StringBuffer class, the result will be different, and each result will operate on the StringBuffer object itself, instead of generating a new object and changing the object reference. So in general we recommend the use of StringBuffer, especially if the string object is constantly changing. In some special cases, string object concatenation is actually interpreted by the JVM as a concatenation of StringBuffer objects, so the speed of a string object is not slower than the StringBuffer object, especially in the following string object generation, Stri NG efficiency is far faster than StringBuffer:
String S1 = "This was only a" + "simple" + "test";
StringBuffer Sb = new StringBuilder ("This was only a"). Append ("simple"). Append ("test");
You'll be surprised to find that the speed at which the String S1 object is generated is simply too fast, and at this point the stringbuffer is not at all dominant at all. In fact, this is a JVM trick, in the JVM's eyes, this
String S1 = "This was only a" + "simple" + "test"; is actually:
String S1 = "This was only a simple test"; So of course it doesn't take much time. But it is important to note that if your string is from another string object, the speed is not so fast, for example:
String S2 = "This was only a";
String S3 = "simple";
String S4 = "Test";
String S1 = S2 +s3 + S4;
At this point the JVM will behave in the same way as it did.

In most cases StringBuffer > String
StringBuffer
Java.lang.StringBuffer A variable sequence of characters for thread safety. A string-like buffer, but cannot be modified. Although it contains a specific sequence of characters at any point in time, some method calls can change the length and content of the sequence.
String buffers can be safely used with multiple threads. These methods can be synchronized if necessary, so all operations on any particular instance appear to occur in a serial order that is consistent with the sequence of method calls made by each thread involved.
The main operations on StringBuffer are the Append and insert methods, which can be overloaded to accept arbitrary types of data. Each method effectively converts the given data into a string, and then appends or inserts the character of the string into the string buffer. The Append method always adds these characters to the end of the buffer, while the Insert method adds characters at the specified point.
For example, if z refers to a string buffer object where the current content is "start", this method call Z.append ("le") causes the string buffer to contain "startle", and Z.insert (4, "le") will change the string buffer to contain " Starlet ".
In most cases StringBuilder > StringBuffer
Java.lang.StringBuilde
Java.lang.StringBuilder A variable sequence of characters is 5.0 new. This class provides an API that is compatible with StringBuffer, but does not guarantee synchronization. This class is designed to be used as a simple replacement for stringbuffer, which is common when a string buffer is used by a single thread. If possible, it is recommended that this class be preferred because, in most implementations, it is faster than StringBuffer. The two methods are basically the same.
=========================================================================
Detailed description of the String class
1. The string class is final and cannot be inherited.
2, the String class is the essence of the character array char[], and its value cannot be changed. PRivate final char value[];
Then open the API documentation for the string class to discover:
3, the String class object has a special way to create, is directly specified such as String x = "abc", "ABC" represents a String object. And X is the address of the "ABC" object, also called

Make a reference to the "ABC" object.
4. String objects can be concatenated by "+". A new string is generated after concatenation. It can also be concatenated by concat (), which is explained later.
6. The Java runtime maintains a string pool, Javadoc translation is very vague "string buffer". The string pool is used to hold the various strings produced in the runtime,

and the contents of the strings in the pool are not duplicated. The normal object does not exist in this buffer pool, and the object created only exists in the stack area of the method.


5, a lot of ways to create strings, summed up there are three categories:
First, create a string using the new keyword, such as string S1 = new String ("abc");
Second, direct designation. For example, string s2 = "abc";
Third, use concatenation to generate a new string. For example, string s3 = "AB" + "C";

Second, the creation of a string object

The creation of string objects is also very important, the key is to understand its principle.
Principle 1: When using any way to create a string object s, the Java runtime (the running JVM) takes this x in the string pool to find out if there is a string object of the same content.

If it does not exist, a string s is created in the pool, otherwise it is not added in the pool.

In principle 2:java, whenever you use the New keyword to create an object, you must create a new object (in the heap or stack area).

Principle 3: Creating a String object using direct designations or concatenation with a pure string will simply check the string in the maintenance string pool without creating one in the pool.

The However, the string object will never be created in the stack area again.

Principle 4: Creating a String object with an expression containing a variable will not only examine the maintenance of the string pool, but also create a string object in the stack area.

In addition, the Intern () method of string is a local method, defined as public native String intern (); The value of the intern () approach is to allow developers to focus on

The string pool. When the Intern method is called, if the pool already contains a string equal to this string object (the object is determined by the Equals (object) method), the return pool

The string in the. Otherwise, this string object is added to the pool, and a reference to this string object is returned.

Third, immutable class
An immutable string has a great advantage: The compiler can set the string to be shared.
Immutable classes string has an important advantage-they are not shared references.

In this case, Java is specially handled for string types for efficiency purposes--a string pool for string types
There are two ways to define a variable of type string:
String name= "Tom";
String name =new string ("Tom")
Using the first method, you use a bunch of pools,
When you use the second way, it's a common way of declaring objects.
If you use the first way, then when you declare a string that is "Tom", it will use the original memory in the pool without reallocating the memory, that is, string saname= "Tom" will point to the same piece of memory

In addition, the question about the type of string is immutable:
The string type is immutable, meaning that when you want to change a string object, such as Name= "Madding"
Then the virtual machine does not change the original object, but instead generates a new string object, and then lets name point to it, if the original "Tom" does not have any objects to reference it, the virtual machine garbage collection mechanism will receive it.
It is said that this can improve efficiency!!!
=========================================================================final StringBuffer a = new StringBuffer (" 111 ");
Final StringBuffer B = new StringBuffer ("222");
a=b;//This sentence compilation does not pass
Final StringBuffer a = new StringBuffer ("111");
A.append ("222");//Compile Through
As you can see, final is valid only for the reference "value" (that is, the memory address), which forces the reference to point only to the object that was initially pointed to, and changes its point to cause a compile-time error. Final is not responsible for the change in the object it points to.

Four examples of a string constant pool problem
Here are a few common examples of comparative analysis and understanding:

[1]
String a = "A1";
String B = "a" + 1;
System.out.println ((A = = b)); result = True
String a = "atrue";
String B = "a" + "true";
System.out.println ((A = = b)); result = True
String a = "a3.4";
String B = "a" + 3.4;
System.out.println ((A = = b)); result = True
Analysis: JVM for string constant "+" number connection, the program compile period, the JVM will be the constant string "+" connection optimization to the concatenated value, take "a" + 1, the compiler is optimized in class is already A1. The value of its string constants is determined at compile time, so the final result of the above program is true.

[2]
String a = "AB";
String BB = "B";
String B = "a" + BB;
System.out.println ((A = = b)); result = False
Analysis: JVM for string reference, because in the string "+" connection, there is a string reference exists, and the reference value in the program compilation period is not determined, that is, "a" + BB can not be optimized by the compiler, only during the program run time to dynamically allocate and the new address after the connection to B. So the result of the above program is also false.

[3]
String a = "AB";
Final String bb = "B";
String B = "a" + BB;
System.out.println ((A = = b)); result = True
Analysis: The only difference between [3] is that the BB string has a final decoration, and for a final modified variable, it is parsed at compile time to a local copy of the constant value stored in its own constant pool or embedded in its byte stream.
So at this point the "a" + BB and "a" + "B" effect is the same. Therefore, the result of the above program is true.

[4]
String a = "AB";
Final String bb = GETBB ();
String B = "a" + BB;
System.out.println ((A = = b)); result = False
private static String GETBB () {return "B";}
Analysis: The JVM for the string reference BB, its value in the compilation period can not be determined, only after the program run time call method, the return value of the method and "a" to dynamically connect and assign the address to B, so the result of the above program is false.

From the above 4 examples can be obtained:

String s = "a" + "B" + "C"; is equivalent to string s = "abc";

String a = "a";
String B = "B";
String c = "C";
String s = a + B + C;
This is not the same, the end result equals:

StringBuffer temp = new StringBuffer ();
Temp.append (a). Append (b). append (c);
String s = temp.tostring ();
From the above analysis results, it is not difficult to infer that the string using the Join operator (+) inefficiency reason analysis, such as the code:

public class Test {
public static void Main (String args[]) {
String s = null;
for (int i = 0; i < i++) {s + = "a";}
}
}
Every time you do it, you produce a StringBuilder object and then throw it away after append. The next time the loop arrives, it re-generates the StringBuilder object and then append the string so that it loops until the end. If we use the StringBuilder object directly for Append, we can save N-1 time to create and destroy objects. So for applications that want to concatenate strings in a loop, the StringBuffer or Stringbulider objects are generally used for append operations.

Intern method of string object understanding and Analysis
public class Test4 {
private static String a = "AB";
public static void Main (string[] args) {
String S1 = "a";
String s2 = "B";
String s = s1 + s2;
System.out.println (s = = a);//false
System.out.println (s.intern () = = a);//true
}
}
The problem with Java is that it is a constant pool. For the s1+s2 operation, a new object is recreated in the heap, and s holds the contents of the new object in the heap space, so s is not equal to the value of a. When you call the S.intern () method, you can return the address value of s in the constant pool, because the value of a is stored in a constant pool, so the values of s.intern and a are equal.
  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.