将三种方法循环1000万次,代码:
1.public class sbbm {
2.
3. static String a;
4. static long time ;
5. public static void main( String[] args ) throws Exception {
6.
7. StringBuilder sb = new StringBuilder();
8. StringBuilder sb3 = new StringBuilder();
9.
10. time = System.currentTimeMillis();
11. for( int i = 0; i < 10000000; i++ ) {
12. StringBuilder sb2 = new StringBuilder();
13. sb2.append( "someStr6ing" );
14. sb2.append( "someS5tring2" );
15. sb2.append( "some3Strin4g" );
16. sb2.append( "so3meStr5ing" );
17. sb2.append( "so2meSt7ring" );
18. a = sb2.toString();
19. }
20. System.out.println( "Way2="+(System.currentTimeMillis()-time) );
21.
22.
23. time = System.currentTimeMillis();
24. for( int i = 0; i < 10000000; i++ ) {
25. sb.delete( 0, sb.length() );
26. sb.append( "someString" );
27. sb.append( "someString2" );
28. sb.append( "someStrin4g" );
29. sb.append( "someStr5ing" );
30. sb.append( "someSt7ring" );
31. a = sb.toString();
32. }
33. System.out.println( "Way1="+(System.currentTimeMillis()-time) );
34.
35. time = System.currentTimeMillis();
36. for( int i = 0; i < 10000000; i++ ) {
37.
38. sb3.setLength( 0 );
39. sb3.append( "someStr55ing" );
40. sb3.append( "some44String2" );
41. sb3.append( "som55eStrin4g" );
42. sb3.append( "some66Str5ing" );
43. sb3.append( "so33meSt7ring" );
44. a= sb3.toString() ;
45. }
46. System.out.println( "Way3="+(System.currentTimeMillis()-time) );
47.
48.
49. }
50.}
注意append的字符串要都不同样,否则会由于java 的String pool对结果造成影响(即3好于2)
结果:
1.Way2=9438
2.Way1=6281
3.Way3=6469
能够将各方法多反复几次,点到顺序,等
整体来看:方法2好于方法3好于方法1
原文:http://www.cnblogs.com/bhlsheji/p/4290917.html