The difference between String, StringBuffer, and Stringbuild

Source: Internet
Author: User
Tags stringreplace

  • Public class Test1 {
  • public static void StringReplace (String text) {
  • Text = Text.replace (' j ',' I ');
  • System.out.println (text);
  • }
  • public static void Stringbufferreplace (StringBuffer text) {
  • Text = Text.append ("C");
  • System.out.println (text);
  • }
  • public static void Main (String args[]) {
  • String stringtext = new String ("Java");
  • StringBuffer buffertext = new StringBuffer ("Java");
  • StringReplace (Stringtext);
  • Stringbufferreplace (Buffertext);
  • System.out.println (stringtext+"/t" +buffertext);
  • }
  • }

The result of the output is:

Iava

Javac

Java Javac

This is because the seventh line of text = Text.append ("C"), the Append method changes the value in text, and the text is the same as the address that the textbuffer points to. So you print Javac

Let me give you an example:

String a = "a"; Suppose a points to address 0x0001

A = "B";//re-assigns a point to address 0x0002, but "a" saved in the 0x0001 address still exists, but it is no longer pointed to by a.

So the operation of string is to change the assignment address instead of changing the value operation

The main performance difference between the string type and the StringBuffer type is actually that the string is immutable (why?). Ask the Java designer, why is String not a native type? Therefore, 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, so it is best not to use string to change the content of the strings, because each generation of the object will have an impact on the system performance, Especially when there are no more reference objects in memory, the JVM's GC will start to work, and the speed will be quite slow. Here is an example that is not very appropriate:

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

If this is the case, after the for loop, if the in-memory objects are not cleaned out by the GC, there is a total of more than 20,000 in memory, a staggering number, and if this is a lot of people use the system, so the number is not much, so you must be careful when using.

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

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

You'll be surprised to find that the speed at which the String S1 object is generated is simply too fast, and at this point the stringbuffer is not at all dominant at all. In fact, this is a JVM trick, in the JVM's eyes, this

String S1 = "This was only 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:

String S2 = "This was 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

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

Java.lang.StringBuffer A variable sequence of characters for thread safety. String-like buffer that resembles string, but cannot be modified. String buffers can be safely used with multiple threads. These methods can be synchronized if necessary, so all operations on any particular instance appear to occur in a serial order that is consistent with the sequence of method calls made by each thread involved.

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.0, an equivalence class, StringBuilder, is added to this class for use by a single thread. 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.

However, it is not safe to use an instance of StringBuilder for multiple threads. For such synchronization, it is recommended to use StringBuffer.

This is to say that everyone can understand the difference between them, then we do a general deduction:

In most cases StringBuilder > StringBuffer

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

Since there is such a derivation, let's do a test to verify:

The test code is as follows:

public class Testssb {

/** creates a new instance of TESTSSB */final static int ttime = 10000;//test cycle 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 is used for:" + (Over-begin) + "MS");}

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 is used for:" + (Over-begin) + "MS");}

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 is used for:" + (Over-begin) + "MS");}

Tests for string concatenation directly on strings public void Test2 () {string s2 = ' ABADF '; long begin = System.currenttimemillis (); for (int i=0;i& lt;ttime;i++) {String s = s2 + s2 + s2;} long over = System.currenttimemillis (); System.out.println ("Action string object reference additive type is used for:" + (Over-begin) + "MS");}

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 operation string is added in time:" + (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 NetBeans 5.0 ide/jdk1.6, and the number of cycles ttime to 10,000 tests results as follows: Operation java.lang.String type is used for: 4392 milliseconds Operation java.lang.String The Buffer type uses a time of 0 milliseconds to operate the Java.lang.StringBuilder type using the time: 0 milliseconds Action string object reference the additive type is used for the time: 15 milliseconds The operation string is added using the time: 0 milliseconds

I can't seem to see the difference between StringBuffer and StringBuilder, add ttime to 30,000 times: Operation java.lang.String type is used for: 53444 milliseconds Operation Java.lang.StringBu The Ffer type is used for a period of 15 milliseconds operation Java.lang.StringBuilder type is used for: 15 MS Action string Object reference the additive type is used for: 31 milliseconds The operation string is added using the time: 0 milliseconds

StringBuffer and StringBuilder performance is still not much difference, and then to 100000 to see, this does not add to the string type test, because the string type of such a large amount of data testing will be very slow ... Operation Java.lang.StringBuffer type is used for: 31 ms Operation Java.lang.StringBuilder type is used for: 16 ms

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

Some are less different, and the results are very stable, and then look at the big point, Ttime = 5000000:

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

Oh, forget, do not go to test, basically is in the performance is StringBuilder > StringBuffer > String.

Summary: String stringbuffer StringBuilder 1.jdk version Support StringBuilder JDK1.5 later version support 2. Thread Safety stringbuffer thread safety StringBuilder thread insecure Java.lang.StringBuffer A variable sequence of characters for thread safety. String-like buffer that resembles string, but cannot be modified. String buffers can be safely used with multiple threads. These methods can be synchronized if necessary, so all operations on any particular instance appear to occur in a serial order that is consistent with the sequence of method calls made by each thread involved. 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.0, an equivalence class, StringBuilder, is added to this class for use by a single thread. 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. However, it is not safe to use an instance of StringBuilder for multiple threads. For such synchronization, it is recommended to use StringBuffer. 3. Speed in general, speed from fast to slow: stringbuilder>stringbuffer>string. When you need to use string concatenation multiple times in a loop, build StringBuilder or StringBuffer. When the order of magnitude is in millions (which may not be accurate here), the speed of StringBuilder is manifested. 4. Parameter transfer problem method a () {String str; ...; b (str);//Call the B method, process str} method B (String str) {str= "Test";} at this time, str in method A does not change because STR is re-allocated memory when str= "test"

The difference between String, StringBuffer, and Stringbuild

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.