Deep analysis of StringBuffer and Stringbuider_java in Java programming

Source: Internet
Author: User
Tags memory usage stringbuffer

The value of string is immutable, and each operation on string generates a new string object, not only inefficient, but also 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, which, when processed, does not generate new objects and is superior to string in memory usage.

StringBuffer allocates a 16-byte length buffer by default, and when the string exceeds that size, the buffer length is automatically increased rather than the new object is generated.

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

StringBuffer str1 = new StringBuffer (); Allocates 16-byte-length buffers
stringbuffer str2 = =new StringBuffer (512);//allocating 512 byte-length buffers
//storing strings in buffers, A 16-byte-length empty buffer
stringbuffer STR3 = new StringBuffer (www.weixueyuan.net) is reserved at the back;


the main methods of the StringBuffer class

The methods in the StringBuffer class focus primarily on manipulating strings, such as Append, insert, and delete, which is also the main difference between the StringBuffer class and the String class. In actual development, if you need to make frequent changes to a string, it is recommended that you use StringBuffer.
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 invoked, the contents of the StringBuffer object also change, for example:

StringBuffer str = new StringBuffer ("biancheng100");
Str.append (TRUE);


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

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

In this way, the string connection operation more than stringbuffer some additional operations, the efficiency of the inevitable discount.

However, for smaller strings, the "+" operation is more intuitive, more readable, and sometimes a bit more efficient.
2) Deletecharat ()

The Deletecharat () method deletes the character at the specified position and forms the remaining characters into a new string. For example:

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


The code deletes the character with the index value of 3, which is the "D" character.

You can also delete more than one character at a single pass by the Delete () method, for example:

StringBuffer str = new StringBuffer ("abcdef");
Str.delete (1, 4);


The code deletes the characters between the index values of 1~4, including the index value 1, but not 4.
3) Insert () method

Insert () is used to insert a string at a specified location, which can be considered an upgraded version of Append (). For example:

StringBuffer str = new StringBuffer ("abcdef");
Str.insert (3, "XYZ");


The last str points to a string of Abcdxyzef.
4) Setcharat () method

The Setcharat () method modifies the character at the specified location. For example:

StringBuffer str = new StringBuffer ("abcdef");
Str.setcharat (3, ' z ');


The code modifies the character with the index value of 3 to Z, and the string to which the last str points is abczef.

These are just a few simple explanations for some of the common methods, and consult the API documentation for more methods and explanations.
Comparison of the efficiency of string and StringBuffer

To make it more obvious how efficiently they are executed, the following code adds 26 English letters 10,000 times.

public class Demo {public
  static void Main (string[] args) {
    String fragment = "abcdefghijklmnopqrstuvwxyz";
    int times = 10000;
    Long TimeStart1 = System.currenttimemillis () by string object;
    String str1 = "";
    for (int i=0; i<times; i++) {
      str1 + = fragment;
    }
    Long timeEnd1 = System.currenttimemillis ();
    System.out.println ("String:" + (TIMEEND1-TIMESTART1) + "MS");
    
    Through StringBuffer
    long timeStart2 = System.currenttimemillis ();
    StringBuffer str2 = new StringBuffer ();
    for (int i=0; i<times; i++) {
      str2.append (fragment);
    }
    Long TimeEnd2 = System.currenttimemillis ();
    System.out.println ("StringBuffer:" + (TIMEEND2-TIMESTART2) + "MS");
  }

Run Result:

String:5287ms
stringbuffer:3ms

Conclusion It is obvious that the execution efficiency of stringbuffer is thousand times faster than that of string, this difference is more and more obvious with the increase of superposition number, when the superposition number reaches 30,000, the running result is:

STRING:35923MS
stringbuffer:8ms

Therefore, it is strongly recommended that you use StringBuffer when a large number of string operations are involved.
StringBuilder class

The StringBuilder class and the StringBuffer class function are basically similar, the methods are the same, the main difference is that the StringBuffer class method is multi-threaded 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 string manipulation, which includes only length (), charAt (int index), subsequence (int start, int end) APIs.

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

It is visible that string implements the Charsequence interface directly; StringBuilder and StringBuffer are variable sequences of characters that inherit from Abstractstringbuilder and implement the Charsequence interface.
Summary

Thread Safety:

StringBuffer: Thread safe
StringBuilder: Thread not secure

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

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

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.