Recently I wrote a plug-in that may consider String concatenation. I thought about several methods, but the performance was unknown. So I used JUnit to write a unit test.
The Code is as follows:
- Import java. util. arraylist;
- Import java. util. List;
- Import org. Apache. commons. Lang. stringutils;
- Import org. JUnit. test;
- Import org. slf4j. Logger;
- Import org. slf4j. loggerfactory;
- Public class teststring {
- Private Final logger = loggerfactory. getlogger (this. getclass ());
- @ Test
- Public void testplus (){
- String S = "";
- Long Ts = system. currenttimemillis ();
- For (INT I = 0; I <10000; I ++ ){
- S = S + String. valueof (I );
- }
- Long TE = system. currenttimemillis ();
- Logger.info ("+ cost {} ms", te-ts );
- }
- @ Test
- Public void testconcat (){
- String S = "";
- Long Ts = system. currenttimemillis ();
- For (INT I = 0; I <10000; I ++ ){
- S = S. Concat (string. valueof (I ));
- }
- Long TE = system. currenttimemillis ();
- Logger.info ("Concat cost {} ms", te-ts );
- }
- @ Test
- Public void testjoin (){
- List <string> List = new arraylist <string> ();
- Long Ts = system. currenttimemillis ();
- For (INT I = 0; I <10000; I ++ ){
- List. Add (string. valueof (I ));
- }
- Stringutils. Join (list ,"");
- Long TE = system. currenttimemillis ();
- Logger.info ("stringutils. Join cost {} ms", te-ts );
- }
- @ Test
- Public void teststringbuffer (){
- Stringbuffer sb = new stringbuffer ();
- Long Ts = system. currenttimemillis ();
- For (INT I = 0; I <10000; I ++ ){
- SB. append (string. valueof (I ));
- }
- SB. tostring ();
- Long TE = system. currenttimemillis ();
- Logger.info ("stringbuffer cost {} ms", te-ts );
- }
- @ Test
- Public void teststringbuilder (){
- Stringbuilder sb = new stringbuilder ();
- Long Ts = system. currenttimemillis ();
- For (INT I = 0; I <100000; I ++ ){
- SB. append (string. valueof (I ));
- }
- SB. tostring ();
- Long TE = system. currenttimemillis ();
- Logger.info ("stringbuilder cost {} ms", te-ts );
- }
- }
The running result is as follows:
11:00:22, 359 info teststring: 23-+ cost 1828 MS
11:00:22, 921 info teststring: 34-Concat cost 562 MS
11:00:22, 937 info teststring: 46-stringutils. Join cost 16 MS
11:00:22, 968 info teststring: 58-stringbuffer cost 31 MS
11:00:23, 031 info teststring: 70-stringbuilder cost 63 MS
Note:
The number of stringbuilder loops is 10 times the number of other loops. If the number is the same, 0 is returned, which shows that stringbuilder is faster.
Summary:
The efficiency of using + is the worst. Because Concat is implemented by internal mechanisms, it is much better than the + method.
Join and stringbuffer are not much different. The join method is faster. It can be seen that this method of rapid String concatenation in Javascript is also very suitable in Java.
Stringbuilder has the fastest speed, but it has thread security issues and is only supported by jdk5.