The differences between the string, StringBuilder, and StringBuffer classes of Java

Source: Internet
Author: User

The StringBuffer class (or StringBuilder), like String, is also used to represent strings, but because StringBuffer is not implemented in the same way as String, StringBuffer is doing string processing. New objects are not generated and are superior to the string class in memory usage.

So in the actual use, if you often need to modify a string, such as inserting, deleting and so on, use StringBuffer to be more appropriate.

There are many methods in the StringBuffer class that are the same as the string class, which are functionally identical to the functions in the string class.

One of the most notable differences, however, is that each modification of a StringBuffer object alters the object itself, which is the biggest difference from the string class.

In addition, because StringBuffer is thread-safe, the concept of threading is followed by specific chapters, so it can be easily used in multithreaded programs, but the execution efficiency of the program will be slightly slower.

1. Initialization of StringBuffer objects

The initialization of the StringBuffer object is not the same as the initialization of the string class, Java provides special syntax, and typically is initialized with a constructor method.
For example:

     StringBuffer s = new StringBuffer();

The

StringBuffer object that is initialized in this way is an empty object.
If you need to create a StringBuffer object with content, you can use:
StringBuffer s = new StringBuffer ("abc");
the contents of the StringBuffer object initialized in this way are the string "abc".
Note that StringBuffer and string are of different types and cannot be cast directly, and the following code is wrong:

StringBuffer s = “abc”;        //赋值类型不匹配//不存在继承关系,无法进行强转StringBuffer对象和String对象之间的互转的代码如下:         String s = “abc”;         new StringBuffer(“123”);         new StringBuffer(s);   //String转换为StringBuffer         String s1 = sb1.toString();              //StringBuffer转换为String
2. Common methods of StringBuffer

The methods in the StringBuffer class mainly focus on changes to strings, such as Append, insert, and delete, which are the main differences between the StringBuffer and the string classes.
A, Append method
Public StringBuffer Append (Boolean B)
The function of this method is to append the content to the end of the current StringBuffer object, similar to a string connection. After the method is called, the contents of the StringBuffer object also change, for example:
StringBuffer sb = new StringBuffer ("abc");
Sb.append (TRUE);
The value of the object SB will become "Abctrue".
Using this method to concatenate strings will save more content than string, such as a connection applied to a database SQL statement, such as:

new StringBuffer();String user = “test”;String pwd = “123”;sb.append(“selectfromwhere username=“)          .append(user)          and pwd=”)          .append(pwd);

The value of this object SB is the string "select * from UserInfo where username=test and pwd=123".

B, Deletecharat method
Public stringbuffer deletecharat (int index)
The function of this method is to delete the character at the specified position and then form the remaining content into a new string. For example:

StringBuffer sb = new StringBuffer(“Test”);sb. deleteCharAt(1);

The function of the code is to delete the string object SB in the index value of 1 characters, that is, to delete the second character, the remaining content constitutes a new string. So the value of the object SB becomes "Tst".
There is also a function-like Delete method:
Public StringBuffer Delete (int start,int end)
The function of this method is to delete all characters within the specified interval, including the start, which does not contain the range of the end index value. For example:

newdelete (1,4);

The purpose of the code is to remove all characters between the index value 1 (including) to the index value 4 (not included), and the remaining characters to form a new string. The value of the object SB is "Tstring".
C, insert method
Public stringbuffer Insert (int offset, Boolean b)
The function of this method is to insert content into the StringBuffer object and then form a new string. For example:

StringBuffer sb = new StringBuffer(“TestString”);sb.insert(4,false);

The purpose of the sample code is to insert a false value at the index value 4 of the object SB, to form a new string, then the value of the object SB after execution is "testfalsestring".
D, Reverse method

Public StringBuffer Reverse ()

The function of this method is to invert the contents of the StringBuffer object and then form a new string. For example:

new StringBuffer(“abc”);sb.reverse();

When you turn, the content in the object SB becomes "CBA".
E, Setcharat method

public void Setcharat (int index, char ch)

The function of this method is to modify the character of the index value in the object to be the new character Ch. For example:
StringBuffer sb = new StringBuffer ("abc");
Sb.setcharat (1, ' D ');
The value of the object SB will become "ADc".

F, TrimToSize method
public void TrimToSize ()

The purpose of this method is to reduce the space waste by narrowing the storage space of the StringBuffer object to the same length as the string length.
In short, in the actual use, string and stringbuffer each have advantages and disadvantages, according to the specific use of the environment, select the corresponding type to use.

Efficiency comparison of String and StringBuffer

In order to see more clearly the efficiency of their execution, the following code adds 26 English letters 10,000 times.

 Public classDemo { Public Static void Main(string[] args) {String fragment ="ABCDEFGHIJKLMNOPQRSTUVWXYZ";intTimes =10000;//Through a String object        LongTimeStart1 = System.currenttimemillis (); String str1 =""; for(intI=0; i<times;        i++) {str1 + = fragment; }LongTimeEnd1 = System.currenttimemillis (); System. out. println ("String:"+ (TIMEEND1-TIMESTART1) +"MS");//through StringBuffer        LongTimeStart2 = System.currenttimemillis (); StringBuffer str2 =NewStringBuffer (); for(intI=0; i<times;        i++) {str2.append (fragment); }LongTimeEnd2 = System.currenttimemillis (); System. out. println ("StringBuffer:"+ (TIMEEND2-TIMESTART2) +"MS"); }}

Operation Result:

String5287msStringBuffer3ms

Conclusion it is clear that the execution efficiency of StringBuffer is more than a few times faster than string, this difference is more and more obvious with the increase of the number of stacks, when the number of stacks reaches 30,000, the result is:
String:35923ms
Stringbuffer:8ms

Therefore, it is strongly recommended to use StringBuffer when dealing with a large number of string operations.

StringBuilder class

The StringBuilder class and the StringBuffer class function are basically similar, the method is also similar, the main difference is that the StringBuffer class method is multithreaded security, and StringBuilder is not thread-safe, compared to, The StringBuilder class will be slightly faster.

The Charsequence interface is implemented in StringBuffer, StringBuilder, and string.

Charsequence is an interface that defines a string operation that includes only the length (), charAt (int index), subsequence (int start, int end) APIs.

The StringBuffer, StringBuilder, and string implementations of the Charsequence interface are different, as shown in:

As can be seen, string directly implements the Charsequence interface; StringBuilder and stringbuffer are variable sequences of characters, all of which inherit from Abstractstringbuilder and implement the Charsequence interface.

In the implementation of JDK, both StringBuffer and StringBuilder inherit from Abstractstringbuilder, For multi-threaded security and non-security see stringbuffer in front of the method of a heap of synchronized is probably understood.

We know that using StringBuffer is nothing more than a way to improve the efficiency of string connections in Java, because the JVM creates multiple string objects by directly using + for string connections, thus causing some overhead.
A char array is used in Abstractstringbuilder to hold the string that needs to be append, and the char array has an initial size that dynamically expands the char array when the string length of append exceeds the capacity of the current char array. That is, re-apply a larger memory space, and then copy the current char array to a new location, because the cost of reallocating memory and copying is relatively large, so each re-application of memory space is a request greater than the current need of memory space, here is twice times.

The classifications are summarized as follows:
(1) StringBuffer in the append operation, just after the string to append, the process is to determine whether the pre-stored array size is more than the first set of 16 sub-characters, and then can be appended, each result will be StringBuffer Object itself, instead of generating a new object, and then changing the object reference. Because StringBuilder and stringbuffer themselves are inherited from Abstractstringbuilder, the Append method in the Abstractstringbuilder class is used when the append operation is performed. All the overloaded append methods in the Abstractstringbuilder class are shown, and different functions can be implemented according to different requirements.

Take append (Charsequence s) as an example to show: (The methods below are all the methods in Abstractstringbuilder)

 @Override  public  abstractstringbuilder append  (charsequence s) {if  (s = = null ) return Appendnull (); if             (s instanceof  String) return         this . Append ((String) s); if             (s instanceof  abstractstringbuilder) return         this . Append ((Abstractstringbuilder) s); return     this . Append (S, 0 , S.length ()); }

The first thing to do is to determine if it is empty, then determine which instance it is, and then end up with another overloaded method of append:

@Override PublicAbstractstringbuilder Append (charsequence s,intStartint End) {if(s = =NULL) s ="NULL";if(Start <0) || (Start >End) || (End> s.length ())) throwNewIndexoutofboundsexception ("Start"+ Start +", End"+End+", S.length ()"+ s.length ());int Len=End-Start; Ensurecapacityinternal (Count +Len); for(inti = start, j = count; I <End;        i++, J + +) Value[j] = S.charat (i); Count + =Len;    return this; }

which

    /**     * The count is the number of characters used.     */    int count;    /**     * The value is used for character storage.     */    char[] value;

Can be seen: ensureCapacityInternal(count + len); is a process of expansion, value[j] = s.charAt(i); is to save the process of appending strings, the specific process is the original StringBuffer object on the basis of the first through the expansion, after the addition of operations;

(2) The four construction methods of the StringBuffer are as follows:

16 个字符。StringBuffer(CharSequence seq)  public java.lang.StringBuilder(CharSequence seq) 构造一个字符串缓冲区,它包含与指定的 CharSequence 相同的字符。StringBuffer(int capacity)   构造一个不带字符,但具有指定初始容量的字符串缓冲区。StringBuffer(String str)  构造一个字符串缓冲区,并将其内容初始化为指定的字符串内容

Each string buffer has a certain amount of capacity. As long as the string buffer contains a sequence of characters that does not exceed this capacity, there is no need to allocate a new array of internal buffers. If an internal buffer overflows, this capacity is automatically incremented. Starting with JDK 5, this class complements the equivalence class used by a single thread, StringBuilder. The StringBuilder class should usually be preferred over this class because it supports all the same operations, but it is faster because it does not perform synchronization.

(3) and for string, although the nature of append (string concatenation) is achieved by creating StringBuilder objects through the StringBuilder append method, But each append process is the process of creating a StringBuilder object at a time, which means that each time the string type is changed it is equivalent to generating a new string object, and then pointing the pointer to the new string object. Efficiency is obviously much lower than the direct use of StringBuilder, there are many test experiments on the Internet, but also fully illustrate this point, so often change the content of the string is best not to use string, because each generation of objects will have an impact on system performance, especially when there is no reference object in memory more , the JVM's GC will begin to work, and that speed will certainly be quite slow;

(4) and in some special cases, string object concatenation is actually interpreted by the JVM as StringBuffer object splicing, so the speed of the string object is not slower than the StringBuffer object, and especially the following string object generation, S Tring efficiency is far faster than StringBuffer:

Stringisnewis only a”).append(“ simple”).append(“ test”);

Will be surprised to find that the speed of generating a String S1 object is simply too fast, and this time stringbuffer incredibly speed is not at all dominant. In fact, it's a trick of the JVM, in the JVM's eyes, this string S1 = "The is just a" + "simple" + "test";
It 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:

Stringis only a”;String S3 = “ simple”;String S4 = “ test”;String S1 = S2 +S3 + S4;

At this time the JVM will behave in the original way to do, S1 object generation speed is not as fast as it was just now, we can have a test to verify.
Thus we get the first conclusion: in most cases stringbuffer > String

(4) Generally speaking, StringBuilder is suitable for the need for frequent character append delete operation, etc., the original design of the string itself should be in the back of the use of the process, will not be too many additions and deletions, after all, string is final type, is immutable object, So they are good at the place, according to their own needs to make a reasonable choice can;

Summarize

Thread Safety:
StringBuffer: Thread Safety
StringBuilder: Thread is not secure

Speed:
In general, the speed from fast to slow for StringBuilder > StringBuffer > String, of course this is relative, not absolute.

Usage Environment:
Manipulate small amounts of data using String;
Single-threaded operation of large amounts of data using StringBuilder;
Multithreading operations large amounts of data using StringBuffer.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

The differences between the string, StringBuilder, and StringBuffer classes of Java

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.