[Reprinted] Test on string connection efficiency in Java

Source: Internet
Author: User

From: http://xumiao900.iteye.com/blog/477778

Compare the efficiency of connecting strings of the string, stringbuffer, and srtingbuilder objects in Java.

We often hear experienced people say that we should avoid using strings to connect strings through "+ ".
The stringbuffer must be used when the number of connections is large.

Compare who has high efficiency. below is the test code, which can be run directly:
Package cn.com. test;

Public class teststringconnecttime {

// Set the connection time
Private Final int n = 20000;

Public static void main (string [] ARGs ){
Teststringconnecttime test = new teststringconnecttime ();
Test. teststringtime ();
Test. teststringbuffertime ();
Test. teststringbuildertime ();
}

/**
* Test the string connection time
*/
Public void teststringtime (){
Long start = system. currenttimemillis ();
String A = "";
For (int K = 0; k <n; k ++ ){
A + = "_" + K;
}
Long end = system. currenttimemillis ();
Long time = end-start;
System. Out. println ("string time:" + time );
}

/**
* Test the stringbuffer connection string time
*/
Public void teststringbuffertime (){
Long start = system. currenttimemillis ();
Stringbuffer B = new stringbuffer ();
For (int K = 0; k <n; k ++ ){
B. append ("_" + k );
}
Long end = system. currenttimemillis ();
Long time = end-start;
System. Out. println ("stringbuffer time:" + time );
}

/**
* Test the stringbuilder connection string time
*/
Public void teststringbuildertime (){
Long start = system. currenttimemillis ();
Stringbuilder c = new stringbuilder ();
For (int K = 0; k <n; k ++ ){
C. append ("_" + k );
}
Long end = system. currenttimemillis ();
Long time = end-start;
System. Out. println ("stringbuilder time:" + time );
}

}

We tested the time spent connecting the three objects to the string when n = 10,100,500,100, respectively,
Make a simple statistics and get the following data:

Time required for connection count (N) (unit: milliseconds)
String stringbuffer stringbuilder
10 0 0 0
100 0 0 0
500 31 16 0
1000 63 31 16
5000 781 63 47
10000 7547 63 62
20000 62984 94 63

From the comparison of the above chart results, we can clearly see why we encourage the use of stringbuffer to connect strings. Less connections
In this case, the low efficiency of string is not very prominent, but once the number of connections is large, the performance will be greatly affected.
It takes about one minute to connect 20 thousand strings in a row, while stringbuffer only takes 94 milliseconds, with a difference of nearly 500 times. While
The difference between stringbuffer and stringbuilder is not big. stringbuilder is faster than stringbuffer. I think it is because stringbuffer
It is line program security, and stringbuilder is not line program security, so stringbuffer is a little slower.

But why is string so slow? analyze the following code:
String result = "";
Result + = "OK ";
This code has low performance because the string class in Java is immutable ),
By using the javap tool, we can know that the above Code is equivalent to the source code when being compiled into bytecode:
String result = "";
Stringbuffer temp = new stringbuffer ();
Temp. append (result );
Temp. append ("OK ");
Result = temp. tostring ();
How can two short statements become so many? The cause of the problem lies in the immutability of the string class.

Therefore, if you often operate on the content in the string, especially when the content is to be modified, use stringbuffer.
If string is required, use the tostring () method of stringbuffer. However, it is disturbing that the stringbuilder instance is used for multiple threads.
All. If such synchronization is required, stringbuffer is recommended because stringbuffer is thread-safe. In most non-multiple
In thread development, stringbuilder can be used to replace stringbuffer to improve efficiency, which is faster.

Supplement 1:
Public static string concat1 (string S1, string S2, string S3, string S4, string S5, string s6 ){
String result = "";
Result + = S1;
Result + = S2;
Result + = S3;
Result + = S4;
Result + = S5;
Result + = S6;
Return result;
}

Public static string concat2 (string S1, string S2, string S3, string S4, string S5, string s6 ){
Stringbuffer result = new stringbuffer ();
Result. append (S1 );
Result. append (S2 );
Result. append (S3 );
Result. append (S4 );
Result. append (S5 );
Result. append (s6 );
Return result. tostring ();
}

Public static string concat3 (string S1, string S2, string S3, string S4, string S5, string s6 ){
Return new stringbuffer (s1.length () + s2.length () + s3.length () + s4.length () + s5.length () + s6.length ())
. Append (S1). append (S2). append (S3). append (S4). append (S5). append (s6). tostring ();
}

Public static string concat4 (string S1, string S2, string S3, string S4, string S5, string s6 ){
Return S1 + S2 + S3 + S4 + S5 + S6;
}

Public static string concat5 (string S1, string S2, string S3, string S4, string S5, string s6 ){
Return new stringbuilder (s1.length () + s2.length () + s3.length () + s4.length () + s5.length () + s6.length ())
. Append (S1). append (S2). append (S3). append (S4). append (S5). append (s6). tostring ();
}

The first method is the most practical and cumbersome method. In fact, I will have a headache when I see such code.
All the friends who have read cutting-tive Java know how to use stringbuffer. There should be a lot of people using the second method.
Of course, the 4th types of writing methods are the simplest and most beautiful, that is, they don't know what the performance is like.
Java 5 adds a stringbuilder class, which is the same as the stringbuffer function, that is, it is not synchronized,
All replace stringbuffer with stringbuilder will certainly be of good performance, resulting in 5th writing methods.

It is convincing to do a test. I tested JDK 5 and JDK 6 on the same machine.
Each function is executed 10000000 times (each input parameter is "A"). The following statements are used in milliseconds:

JDK 5:
Concat1: 13776
Concat2: 5081
Concat3: 4944
Concat4: 4202
Concat5: 4047

JDK 6:
Concat1: 11801
Concat2: 3930
Concat3: 3976
Concat4: 3353
Concat5: 3440

It can be seen that the 1st writing methods are indeed the slowest, and the second writing method is much faster due to the use of stringbuffer.
The strange thing is that 4th writing methods are actually very fast and faster than stringbuffer. What's wrong?
In fact, if you have debugged the execution process of the string connection, you will know that Java will automatically use the stringbuilder. append () function to connect to the string when you use the 4th writing method.
Therefore, the simplest 4th writing methods are fast enough.
In JDK 5, the 5th statements are the fastest, because the total length is calculated in advance when the stringbuilder is created, eliminating the memory redistribution.
However, there is no need to write this. JDK 6 has already optimized the 4th writing methods, but the 5th writing methods are slow.

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.