Java string connection Efficiency

Source: Internet
Author: User

String operations are the most common behavior in programming. This article analyzes the efficiency of String processing in three categories: String, StringBuilder, and StringBuffer.

The most common and widely used class in Java is the String class.

String: Strings are constant; their values cannot be changed after they are created.

This is JDK's interpretation of String, meaning: String is a constant and its value cannot be modified once it is created.

First, let's look at how the String object is created:

String str1 = "abc ";

String str2 = new String ("abc ");

This is two common forms.

The string created in the first method will be placed in the stack. More specifically, the constant pool is used to store the data that has been determined in the compilation phase, generally, the basic data types such as int are stored here. A specific process is that the compiler first checks the constant pool to see if there is any "abc". If not, it is created. If yes, str1 is directed to that position.

The second method to create a string is to use the new keyword or java memory allocation. java will place the new object in the heap. This part of the object is created at runtime. So every time we create a new object, we will create different objects, even if there is an identical object in the heap.

The following program will verify the above statement.

 1 String str1 = "abc"; 2 String str2 = new String("abc"); 3  4 String str3 = "abc"; 5 String str4 = new String("abc"); 6  7 System.out.println(str1==str2);//false 8          9 System.out.println(str1 == str3);//true10 System.out.println(str2 == str4);//false11 // When the intern method is invoked, if the pool already contains a12 // string equal to this String object as determined by the13 // equals(Object) method, then the string from the pool is returned.14 // Otherwise, this String object is added to the pool and a reference to15 // this String object is returned.16 str2 = str2.intern();17 System.out.println(str1==str2);//true18 19 false20 true21 false22 true

The above four objects are created in two ways, and "=" compares the addresses. From the result, we can see that str1 and str3 are the same and point to the same object. The result returned by comparing str2 and str4 is false, indicating that str2 and str4 are not pointing to the same object.

(An uncommon method is used above: intern. Returns true if str1 and str2 are compared after str2 calls the intern method. You can see from the code comment that the intern method returns the same object as the object in the constant pool, if the constant pool does not exist, add the object to the constant pool .)

The String object remains unchanged. Why can I perform operations such as str + = "abc? In fact, such operations generate a new String object that contains the String after the str and abc connections.

1 package test;2 3 public class StringTest {4     public static void main(String[] args) {5         String str1 = "abc";6         str1 += "123";7     }8 }

From the compiled class, we can see that the compiler automatically introduces the StringBuilder class, creates the StringBuilder object through its initialization method, adds content through the append method, and CALLS toString to return the connected object. The above content proves that the String object is immutable, and the connection operation actually returns a new object. If the connection is made cyclically multiple times, the StringBuilder object, new append content, and toString object will be continuously created. This brings about the efficiency of the String class to process String changes.

 1 public class StringTest { 2     public static void main(String[] args) { 3         long start, end; 4  5         StringBuilder strBuilder = new StringBuilder(" "); 6         start = System.currentTimeMillis(); 7         for (int i = 0; i < 100000; i++) { 8             strBuilder.append(" "); 9         }10         end = System.currentTimeMillis();11         System.out.println("StringBuilder append: " + (end - start) + "ms");12 13         String str = " ";14         start = System.currentTimeMillis();15         for (int i = 0; i < 100000; i++) {16             str += " ";17         }18         end = System.currentTimeMillis();19         System.out.println("String +: " + (end - start) + "ms");20     }21 }

We can see the difference in efficiency between String and StringBuilder.

StringBuffer: A thread-safe, mutable sequence of characters. A string buffer is like a String, but can be modified.

StringBuilder: A mutable sequence of characters. This class provides an API compatible with StringBuffer, but with no guarantee of synchronization.

StringBuffer is a variable, thread-safe string. StringBuilder is the non-thread synchronization version of StringBuffer. The two methods are similar. It is only a thread-safe (applicable to multithreading) and a non-thread-safe (applicable to a single thread ).

 

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.