Java string selection

Let's analyze the string connection.

  1. String

Open the source code of string, as shown in the figure

You will find that the character value of the stored string is a final constant. Looking at the construction method of string, it is found that the value of string is determined in the construction method. It is necessary to explain the keyword final

The attribute of final modification is a constant (the value cannot be changed). It is either assigned at the same time of declaration or in the constructor. Once assigned, it cannot be changed.

Therefore, string is used to realize string splicing. Since the value of string cannot be changed, a new string must be generated for each splicing to store a new string. Therefore, the performance of using string to process string splicing will be very low.

For more information about string, please refer to the blog: http://longpo.iteye.com/blog/2199493

  2. StringBuffer

The StringBuffer class inherits the abstract class abstractstringbuilder class. Open the abstractstringbuilder source code

Let's take a look at the three construction methods of overloading with StringBuffer

The discovery is to call the constructor of the parent class abstractstringbuilder

It is found that the char array of data stored in StringBuffer is not of final type, indicating that it can be changed, and the constructed strings still have free space to splice strings.

In StringBuffer, we use the append () function to splice strings. We can think that although the char array is still left, it is certainly not enough to splice all the time. Therefore, it is necessary to look at the source implementation of the append function.

View the append method of its parent class abstractstringbuilder

It is found that when the capacity of the value array is insufficient, a new value array will be created to store the string. Here you should understand the principle of string buffer string splicing. When the char value array is not enough, a larger capacity array will be created for storage. The efficiency is obviously higher than that of string.

  3. StringBuilder

StringBuilder and StringBuffer are two brothers. Their usage is basically the same. The difference is that StringBuffer is synchronous and thread safe, while StringBuilder does not guarantee synchronization and thread unsafe.

StringBuilder is faster than StringBuffer in most implementations. When the string buffer is accessed by a single thread, it is recommended to use StringBuilder first

The above is the Java string selection introduced by Xiaobian. I hope it will be helpful to you. If you have any questions, please leave me a message, and Xiaobian will reply to you in time. Thank you very much for your support for the programming tips website!

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>