Excerpt from: http://blog.chinaunix.net/uid-20745012-id-271466.html
The StringBuilder does not provide a clear or empty method.
There are 3 ways to clear:
1) Reborn into one, the old is automatically recovered by the system
2) Use Delete
3) Use SetLength
Cycle three methods 10 million times, code:
/** * @ Author WHS * @ creation Date January 30, 2015 * @ Version V 1.0 */package Strdemo;public class Strbuilder {static String a;static long time;p Ublic static void Main (string[] args) {StringBuilder sb = new StringBuilder (); StringBuilder sb2=new StringBuilder (); time = System.currenttimemillis (); for (int i=0;i<10000000;i++) {sb.delete (0, Sb.length ()); Sb.append ("Somethi1ng"); Sb.append ("Somethi2ng"); Sb.append ("Somethi3ng"); Sb.append ("SomeThi4ng"); Sb.append ("Somethi5ng"); Sb.append ("Somethi6ng"); a = Sb.tostring ();} System.out.println ("way1=" + (System.currenttimemillis ()-time)); time = System.currenttimemillis (); for (int i=0;i < 10000000;i++) {sb2.setlength (0); Sb2.append ("somethin1g"); Sb2.append ("somethin2g"); Sb2.append ("someThin3g"); Sb2.append ("somethin4g"); Sb2.append ("somethin5g"); Sb2.append ("somethin6g"); a = Sb2.tostring ();} System.out.println ("way2=" + (System.currenttimemillis ()-time)); Time=system.currenttimemillis (); for (int i=0;i < 10000000;i++) {StringBuilder sb3=new StringBuilder (); Sb3.append ("someThing1"); SB3.append ("SomeThing2"), Sb3.append ("SomeThing3"), Sb3.append ("SomeThing4"), Sb3.append ("SomeThing5"); Sb3.append (" SomeThing6 "); a=sb3.tostring ();} System.out.println ("way3=" + (System.currenttimemillis ()-time));}}
Note that the strings of append are different, otherwise the result will be affected by the Java string pool (that is, Way1 is better than Way2)
Results:
way1=1672
way2=1632
way3=2532
The methods can be repeated several times, point to order, and so on overall: Way2 better than Way1 better than Way3
Comparison of empty methods in Java StringBuilder