Analysis of the difference between Java string, StringBuffer and StringBuilder _java

Source: Internet
Author: User
Tags stringbuffer
I believe that the difference between String and StringBuffer has also been very understanding, but it is estimated that there will be a lot of comrades on the working principle of these two classes are not clear, today I am here to review the concept for you, and by the way pull out J2SE 5.0 Inside brings a new character to operate the class--stringbuilder. So what are the differences between this StringBuilder and StringBuffer and the String class that we first met? What should we use on different occasions? I would like to talk about their views on these categories, but also hope that everyone put forward their opinions, where everyone is wrong, at the same time it is a good opportunity to learn.

Briefly, the main performance difference between a string type and a StringBuffer type is that a string is an immutable object (why?). Ask the Java designer, why is a String not a native type? Therefore, each time a change to the string is equivalent to generating a new string object, and then pointing the pointer at a new string object, it is best not to use string to change the content, because each build object will have an impact on system performance. In particular, the JVM's GC begins to work when there is more than one object in memory, and that speed is bound to be quite slow. Here's an example that is not very appropriate:
Copy Code code as follows:

String S1 = "abc";
for (int I = 0; I < 10000; I + +)//For multiple calls to the emulator
{
S1 + = "def";
S1 = "ABC";
}


If so, after this for loop is finished, if the objects in memory are not cleared by GC, there are more than 20,000 in memory, a staggering number, and if this is a system that many people use, this number is not much, so you must be careful when you use it.

If you use the StringBuffer class, the result is different, and each result operates on the StringBuffer object itself, rather than generating a new object, and then changing the object reference. So in general we recommend using StringBuffer, especially when string objects change frequently. In some special cases, string concatenation of string objects is actually interpreted by the JVM as a concatenation of the StringBuffer objects, so the speed of the string object is not slower than the StringBuffer object, especially in the following string object generation, Stri NG efficiency is far faster than StringBuffer:

Copy Code code as follows:

String S1 = "This are only a" + "simple" + "test";
StringBuffer Sb = new StringBuilder ("This are only a"). Append ("simple"). Append ("test");


You would be surprised to find that the String S1 object was generated at a rate that was simply too fast, and at this point the StringBuffer was not at all dominant in speed. This is actually a trick of the JVM, and in the eyes of the JVM, this
Copy Code code as follows:

String S1 = "This are only a" + "simple" + "test"; In fact, the String S1 = "This is just a simple test"; So of course it doesn't take too much time. But what you should be aware of here is that if your string is from another string object, the speed is not that fast, for example:
String S2 = "This are only a";
String S3 = "simple";
String S4 = "Test";
String S1 = S2 +s3 + S4;

This time the JVM will behave the way it did, and the S1 object will not be built as fast as it was, and we can test it for a while.

This leads us to the first conclusion: in most cases StringBuffer > String

And what about StringBuilder compared to them? First of all, StringBuilder is a newly added class in JDK5.0, which differs from StringBuffer to see the following introduction (source Javaworld):

Java.lang.StringBuffer a sequence of variable characters that is thread safe. String buffer similar to string, but cannot be modified. You can safely use string buffers with multiple threads. These methods can be synchronized as necessary, so all operations on any particular instance occur as if they were in a sequential order, in the same order as the method calls of each of the involved threads.

Each string buffer has a certain capacity. You do not need to allocate a new internal buffer array as long as the string buffer contains a sequence of characters that does not exceed this capacity. This capacity is automatically increased if the internal buffer overflows. Starting with JDK 5.0, it adds an equivalence class for the class that is used by a single thread, that is, StringBuilder. As opposed to this class, the StringBuilder class should generally be used preferentially because it supports all the same operations, but is faster because it does not perform synchronization.

However, it is not safe to use an instance of StringBuilder for multiple threads. It is recommended that you use StringBuffer if you need such a synchronization.

I guess we all know the difference, so let's do a general deduction here:

In most cases StringBuilder > StringBuffer

Therefore, according to the transfer theorem of this inequality: In most cases StringBuilder > StringBuffer > String

Now that we have this derivation, let's do a test to verify that:

The test code is as follows:
Copy Code code as follows:

public class Testssb {

/** creates a new instance of TESTSSB * *
Final static int ttime = 10000;//test cycle count
Public Testssb () {
}

public void Test (String s) {
Long begin = System.currenttimemillis ();
for (int i=0;i<ttime;i++) {
S + + "add";
}
Long over = System.currenttimemillis ();
SYSTEM.OUT.PRINTLN ("Operation" +s.getclass (). GetName () + "type of time used is:" + (Over-begin) + "milliseconds");
}

public void Test (StringBuffer s) {
Long begin = System.currenttimemillis ();
for (int i=0;i<ttime;i++) {
S.append ("add");
}
Long over = System.currenttimemillis ();
SYSTEM.OUT.PRINTLN ("Operation" +s.getclass (). GetName () + "type of time used is:" + (Over-begin) + "milliseconds");
}

public void Test (StringBuilder s) {
Long begin = System.currenttimemillis ();
for (int i=0;i<ttime;i++) {
S.append ("add");
}
Long over = System.currenttimemillis ();
SYSTEM.OUT.PRINTLN ("Operation" +s.getclass (). GetName () + "type of time used is:" + (Over-begin) + "milliseconds");
}

Testing string concatenation of strings directly
public void Test2 () {
String s2 = "ABADF";
Long begin = System.currenttimemillis ();
for (int i=0;i<ttime;i++) {
String s = s2 + s2 + s2;
}
Long over = System.currenttimemillis ();
SYSTEM.OUT.PRINTLN (the time used by the action string object reference additive type is: "+ (Over-begin) +" millisecond ");
}

public void Test3 () {
Long begin = System.currenttimemillis ();
for (int i=0;i<ttime;i++) {
String s = "ABADF" + "ABADF" + "ABADF";
}
Long over = System.currenttimemillis ();
SYSTEM.OUT.PRINTLN (the time used for adding the action string is: "+ (Over-begin) +" milliseconds ");
}

public static void Main (string[] args) {
String S1 = "abc";
StringBuffer sb1 = new StringBuffer ("abc");
StringBuilder SB2 = new StringBuilder ("abc");

TESTSSB t = new TESTSSB ();
T.test (S1);
T.test (SB1);
T.test (SB2);
T.test2 ();
T.test3 ();
}
}

The above code is compiled on the NetBeans 5.0 ide/jdk1.6, and the number of cycles ttime to 10,000 times is as follows:
Operation java.lang.String type used: 4392 ms
Operation Java.lang.StringBuffer Type used: 0 ms
Operation Java.lang.StringBuilder Type used: 0 ms
Action string Object reference additive type used: 15 ms
The action string is added using the time: 0 milliseconds

Seems not to see the difference between StringBuffer and StringBuilder, add ttime to 30,000 times to see:
Operation java.lang.String type used: 53444 ms
Operation Java.lang.StringBuffer Type used: 15 ms
Operation Java.lang.StringBuilder Type used: 15 ms
Action string Object reference additive type used: 31 ms
The action string is added using the time: 0 milliseconds

The performance of StringBuffer and StringBuilder is still not much different, and to 100000 to see, there is no test for string type, because the test of such a large amount of string type is slow ...
Operation Java.lang.StringBuffer type used: 31 ms
Operation Java.lang.StringBuilder Type used: 16 ms

Can see the difference, but there are many test results are stringbuffer faster than StringBuilder, and then add some to 1000000 to see (should not be a machine?) ):
Operation Java.lang.StringBuffer Type used: 265 ms
Operation Java.lang.StringBuilder Type used: 219 ms

Some little difference, and the result is very stable, and then look at the big point, Ttime = 5000000:

······ Exception in thread "main" Java.lang.OutOfMemoryError:Java heap space

Oh, forget, not to test, basically are in the performance are StringBuilder > StringBuffer > String.
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.