误区:大家都说StringBuilder在单线程下比StringBuffer效率高
大家都说StringBuilder在单线程下比StringBuffer效率高,但我的运行结果怎么相反呢??请大家测试一下,并指正。
我的程序如下:
public class StringTest{ public static void main(String args[]){ long startTime1 = System.currentTimeMillis(); String text = ""; for(int i=0;i<10000;i++){ text+=i; } System.out.println(System.currentTimeMillis()-startTime1); long startTime2 = System.currentTimeMillis(); StringBuffer textBuffer = new StringBuffer(""); for(int i=0;i<10000;i++){ textBuffer.append(i); } System.out.println((System.currentTimeMillis()-startTime2)); long startTime3 = System.currentTimeMillis(); StringBuilder textBuilder = new StringBuilder(""); for(int i=0;i<10000;i++){ textBuilder.append(i); } System.out.println((System.currentTimeMillis()-startTime3)); }}
public class StringTest{ public static void main(String args[]){ int max = 1000000; //如果内存足够大,可以改成 max = Integer.MAX_VALUE;// long startTime1 = System.currentTimeMillis();// String text = "";// for(int i=0;i<10000;i++){// text+=i; //这个就不用测了,大家都知道这种是效率最低的// }// System.out.println(System.currentTimeMillis()-startTime1); long startTime2 = System.currentTimeMillis(); StringBuffer textBuffer = new StringBuffer(""); for(int i=0;i<max;i++){ textBuffer.append(i); } System.out.println((System.currentTimeMillis()-startTime2)); long startTime3 = System.currentTimeMillis(); StringBuilder textBuilder = new StringBuilder(""); for(int i=0;i<max;i++){ textBuilder.append(i); } System.out.println((System.currentTimeMillis()-startTime3)); }}