Java StringBuffer and Stringbuider

Source: Internet
Author: User

The value of string is immutable, and each operation on a string generates a new string object that is inefficient and consumes a lot of memory space.

The StringBuffer class, like the string class, is also used to represent strings, but the internal implementation of StringBuffer is different from string, and does not generate a new object for string processing, which is better than string in memory usage.

StringBuffer allocates a 16-byte buffer by default, and when the string exceeds that size, it automatically increases the buffer length instead of generating a new object.

Unlike string, StringBuffer can only create objects from new, and does not support shorthand, for example:

  1. StringBuffer str1 = new stringbuffer(); //Allocate a buffer of 16 bytes in length
  2. StringBuffer str2 = =new stringbuffer(+); //Allocate a buffer of 512 bytes in length
  3. A string is stored in the buffer, and a 16-byte-long empty buffer is reserved behind it
  4. StringBuffer STR3 = new stringbuffer("www.weixueyuan.net");
The main methods of the StringBuffer class

The methods in the StringBuffer class mainly focus on the manipulation of strings, such as Append, insert, and delete, which is also the main difference between the StringBuffer class and the String class. In real-world development, it is recommended to use StringBuffer if you need to make frequent modifications to a string.

1) Append () method

The append () method is used to append content to the end of the current string, similar to a string connection. After the method is called, the contents of the StringBuffer object also change, for example:

    1. StringBuffer str = new stringbuffer("biancheng100");
    2. Str. Append(true);

The value of the object str will become "biancheng100true". Note that the content that Str points to has changed, not the direction of Str.

The "+" operation of the string actually creates a StringBuffer object first, and then calls the Append () method to stitch up the string fragment and finally calls the ToString () method to convert to a string.

In this sense, the connection operation of string is more than stringbuffer some additional operations, the efficiency will inevitably be compromised.

However, for smaller-length strings, the "+" operation is more intuitive, more readable, and sometimes it can be sacrificed a little bit.

2) Deletecharat ()

The Deletecharat () method is used to remove characters from the specified position and to form the remaining characters into a new string. For example:

    1. StringBuffer str = new stringbuffer("abcdef");
    2. Str. Deletecharat(3);

The code will delete the character with an index value of 3, which is the "D" character.

You can also delete multiple characters at once by using the Delete () method, for example:

    1. StringBuffer str = new stringbuffer("abcdef");
    2. Str. Delete(1, 4);

The code deletes the characters between the index values of 1~4, including the index value of 1, but excludes 4.

3) Insert () method

Insert () Inserts a string at the specified location, which can be considered an upgraded version of Append (). For example:

    1. StringBuffer str = new stringbuffer("abcdef");
    2. Str. Insert(3, "xyz");

The last string that str points to is Abcdxyzef.

4) Setcharat () method

The Setcharat () method is used to modify the character at the specified position. For example:

    1. StringBuffer str = new stringbuffer("abcdef");
    2. Str. Setcharat(3, ' z ');

The code modifies the character with index value 3 to Z, and the last str points to a string of Abczef.

These are just a few simple explanations for some of the most common methods, please consult the API documentation for more methods and explanations.

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.

  1. Public class Demo {
  2. public static void main(String[] args){
  3. String Fragment = "abcdefghijklmnopqrstuvwxyz";
  4. int times = 10000;
  5. //Through a String object
  6. long TimeStart1 = System. Currenttimemillis();
  7. String str1 = "";
  8. for (int i=0; I<times; I+ +) {
  9. STR1 + = fragment;
  10. }
  11. long TimeEnd1 = System. Currenttimemillis();
  12. System. Out. println("String:" + (timeEnd1 -timeStart1) + "MS");
  13. //through StringBuffer
  14. long TimeStart2 = System. Currenttimemillis();
  15. stringbuffer str2 = new stringbuffer();
  16. for (int i=0; I<times; I+ +) {
  17. STR2. Append(fragment);
  18. }
  19. long TimeEnd2 = System. Currenttimemillis();
  20. System. Out. println("StringBuffer:" + (timeEnd2 -timeStart2) + "MS");
  21. }
  22. }

Operation Result:
String:5287ms
Stringbuffer:3ms

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:


Figure 1 Implementation of the Charsequence interface


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

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.

Java StringBuffer and Stringbuider

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.