StringBuilder 沒有提供clear或empty方法。
清空有3種方法:
1)新產生一個,舊的由系統自動回收
2)使用delete
3)使用setLength
將三種方法迴圈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