In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly explains "what is the difference between String, StringBuffer and StringBuilder in Java". The content in the article is simple and clear, easy to learn and understand. Please follow the editor's train of thought to study and learn "what is the difference between String, StringBuffer and StringBuilder in Java".
In addition to memory distribution and equals comparison, the most common interview questions about strings are the differences between StringBuffer and StringBuilder.
If you answer: the String class is immutable, StringBuffer and StringBuilder are mutable, StringBuffer is thread-safe, and StringBuilder is not thread-safe.
Concatenation of String strings
Several previous articles on String strings have been described in detail, and its immutability is also caused by the fact that a new string is generated in memory whenever the "+" operation is passed.
String a = "hello"; String b = "world!"; String ab = a + b
Where an and b are initialized in the string constant pool, and the ab spliced objects are in the heap. It is easy to see that the new String object is generated after stitching. If you splice multiple times, multiple intermediate objects will be generated.
The above conclusion is true before Java8. During Java8, JDK optimizes the splicing of the "+" sign, and the stitching method written above will be optimized to be processed by the append method based on StringBuilder.
Stack=2, locals=4 Args_size=1 0: ldc # 2 / / String hello 2: astore_1 3: ldc # 3 / / String world! 5: astore_2 6: new # 4 / / class java/lang/StringBuilder 9: dup 10: invokespecial # 5 / / Method Java/lang/StringBuilder. "": () V 13: aload_1 14: invokevirtual # 6 / / Method java/lang/StringBuilder.append: (Ljava/lang/String ) Ljava/lang/StringBuilder; 17: aload_2 18: invokevirtual # 6 / / Method java/lang/StringBuilder.append: (Ljava/lang/String;) Ljava/lang/StringBuilder; 21: invokevirtual # 7 / / Method java/lang/StringBuilder.toString: () Ljava/lang/String; 24: astore_3 25: return
The above is the result of uncompiling the bytecode through the javap-verbose command. You can obviously see the creation of StringBuilder and the call to the `append method.
At this point, it would be wrong to give a general answer: multiple String objects are created by concatenating strings with plus signs, so the performance is worse than StringBuilder. Because in essence, the effect of plus sign stitching is consistent with StringBuilder after being processed by the compiler.
If you use the following in your code:
StringBuilder sb = new StringBuilder ("hello"); sb.append ("world!"); System.out.println (sb.toString ())
The compiler plug-in even suggests that you use String instead.
Comparison between StringBuffer and StringBuilder
The core code of the StringBuffer and StringBuilder implementations is basically the same, and much of the code is common. Both classes inherit from the abstract class AbstractStringBuilder.
Let's take a look at the differences from constructors to append methods. Let's first take a look at the construction method of StringBuilder:
Public StringBuilder (String str) {super (str.length () + 16); append (str);}
The super method is the constructor of the called AbstractStringBuilder. The same is true for the constructor implementation of the corresponding StringBuffer:
Public StringBuffer (String str) {super (str.length () + 16); append (str);}
In terms of construction method, StringBuffer and StringBuilder are the same. Let's take a look at the append method. The StringBuilder implementation is as follows:
@ Overridepublic StringBuilder append (String str) {super.append (str); return this;}
The corresponding methods for StringBuffer are as follows:
@ Overridepublic synchronized StringBuffer append (String str) {toStringCache = null; super.append (str); return this;}
Obviously, in addition to internally assigning the toStringCache variable to null in the append method implementation of StringBuffer, the only difference is that the method is synchronized using synchronized.
ToStringCache is used to cache the string generated the last time the toString method is called, and this value changes when the StringBuffer content changes.
By comparing the append methods above, we can easily find that StringBuffer is thread-safe and StringBuilder is non-thread-safe. Of course, using synchronized for synchronization results in much lower performance.
The underlying implementation of StringBuffer and StringBuilder
Both StringBuffer and StringBuilder call the constructor of the parent class:
AbstractStringBuilder (int capacity) {value = new char [capacity];}
Through this constructor, we can see that the key attribute they use to process string information is value. During initialization, initialize a char [] array with the length of the incoming string + 16, that is, the value, which is used to store the actual string.
After calling the parent class constructor, the respective append methods are called (see the previous code), and the core processing invokes the parent class's append method:
Public AbstractStringBuilder append (String str) {if (str = = null) return appendNull (); int len = str.length (); ensureCapacityInternal (count + len); str.getChars (0, len, value, count); count + = len; return this;}
In the above code, the str.getChars method is used to concatenate the incoming str string and populate it after the original value array. Count is used to record the length that has been used in the current value number.
So where does thread insecurity occur when synchronized is not used for synchronization? Count+=len in the above code is not an atomic operation. For example, if the current count is 5, two threads perform the + + operation at the same time, and both get a value of 5. After performing the add operation, the value is assigned to count, and both threads are assigned a value of 6 instead of 7. At this point, there is the problem of thread unsafety.
Why is String designed to be immutable
The design of String as immutable in Java is the result of taking various factors into account for the following reasons:
1, the need for string constant pool, if the string is variable, changing one object will affect another independent object. This is also a prerequisite for the existence of a string constant pool.
2. The hash code of the String object in Java is frequently used, such as in containers such as HashMap. The invariance of the string ensures the uniqueness of the hash code, which can be cached and used.
3. Security to ensure that String remains unchanged when passed as a parameter to avoid security risks. For example, the database user name, password, access path and other transmission process remain unchanged to prevent the value of the change string pointing to the object from being changed.
4. Because the string variable is immutable, it can be shared in multithreading.
Thank you for your reading, the above is the content of "what is the difference between String, StringBuffer and StringBuilder in Java". After the study of this article, I believe you have a deeper understanding of what is the difference between String, StringBuffer and StringBuilder in Java. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.