StringBuilder 没有提供clear或empty方法。
清空有3种方法:
1)使用delete
2)新生成一个,旧的由系统自动回收
3)使用setLength
将三种方法循环1000万次,代码:
public class sbbm { static String a; static long time ; public static void main( String[] args ) throws Exception { StringBuilder sb = new StringBuilder(); StringBuilder sb3 = new StringBuilder(); time = System.currentTimeMillis(); for( int i = 0; i < 10000000; i++ ) { sb.delete( 0, sb.length() ); sb.append( "someString" ); sb.append( "someString2" ); sb.append( "someStrin4g" ); sb.append( "someStr5ing" ); sb.append( "someSt7ring" ); a = sb.toString(); } System.out.println( "Way1="+(System.currentTimeMillis()-time) ); time = System.currentTimeMillis(); for( int i = 0; i < 10000000; i++ ) { StringBuilder sb2 = new StringBuilder(); sb2.append( "someStr6ing" ); sb2.append( "someS5tring2" ); sb2.append( "some3Strin4g" ); sb2.append( "so3meStr5ing" ); sb2.append( "so2meSt7ring" ); a = sb2.toString(); } System.out.println( "Way2="+(System.currentTimeMillis()-time) ); time = System.currentTimeMillis(); for( int i = 0; i < 10000000; i++ ) { sb3.setLength( 0 ); sb3.append( "someStr55ing" ); sb3.append( "some44String2" ); sb3.append( "som55eStrin4g" ); sb3.append( "some66Str5ing" ); sb3.append( "so33meSt7ring" ); a= sb3.toString() ; } System.out.println( "Way3="+(System.currentTimeMillis()-time) ); } }
注意append的字符串要都不相同,否则会因为java 的String pool对结果造成影响(即3好于2)
结果:
- Way1=6281
- Way2=9438
- Way3=6469
可以将各方法多重复几次,点到顺序,等
总体来看:方法1最好