StringBuilder几种清空方法的效率比较
分类:Java, Java语言
阅读 (3,107)
Add comments
6月 202016
一共有三种方法可以实现StringBuilder的清空
- New一个新的StringBuilder
- 使用StringBuilder的delete方法
- 使用StringBuilder的setLength方法
下面通过代码验证三种方法的效率
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
public class StringBuilderClearTest { public static void main(String[] args){ long time = System.currentTimeMillis(); System.out.println("begin: " + time); StringBuilder sbMain1 = new StringBuilder(); StringBuilder sbMain2 = new StringBuilder(); StringBuilder sbMain3 = new StringBuilder(); StringBuilder sb1 = null; for(int i=0; i<1000000; i++){ sb1 = new StringBuilder("a1"); sb1.append("a2"); sb1.append("a3"); sbMain1.append(sb1); } long time1 = System.currentTimeMillis(); StringBuilder sb2 = new StringBuilder(); for(int i=0; i<1000000; i++){ sb2.delete(0, sb2.length()); sb2.append("b1"); sb2.append("b2"); sb2.append("b3"); sbMain2.append(sb2); } long time2 = System.currentTimeMillis(); StringBuilder sb3 = new StringBuilder(); for(int i=0; i< 1000000; i++){ sb3.setLength(0); sb3.append("c1"); sb3.append("c2"); sb3.append("c3"); sbMain3.append(sb3); } long time3 = System.currentTimeMillis(); System.out.println(sbMain1.length()); System.out.println(sbMain2.length()); System.out.println(sbMain3.length()); System.out.println("New耗时: " + (time1 - time)); System.out.println("delete耗时: " + (time2 - time1)); System.out.println("setLength: " + (time3 - time2)); } } |
测试了十几次,选了一次比较有代表性的结果:
1 2 3 |
New耗时 90 delete耗时: 73 setLength: 63 |
由结果可见setLength是最快的,delete不相上下,new是最慢的