String与StringBuilder的差距

public class testString {
	public static void main(String[] args) {
		final int TIMES = 1000;
		final int TIMES2 = 10000;
		final int TIMES3 = 100000;
		final String STRING="AAAAAA";
		Long start;
		start=System.currentTimeMillis();
		String s="";
		for (int i = 0; i < TIMES; i++) {
			s+=STRING;
		}
		System.out.println(System.currentTimeMillis()-start);
		
		start=System.currentTimeMillis();
		StringBuilder sbd=new StringBuilder();
		for (int i = 0; i < TIMES; i++) {
			sbd.append(STRING);
		}
		System.out.println(System.currentTimeMillis()-start);
		
		start=System.currentTimeMillis();
		String s2="";
		for (int i = 0; i < TIMES2; i++) {
			s2+=STRING;
		}
		System.out.println(System.currentTimeMillis()-start);
		
		start=System.currentTimeMillis();
		StringBuilder sbd2=new StringBuilder();
		for (int i = 0; i < TIMES2; i++) {
			sbd2.append(STRING);
		}
		System.out.println(System.currentTimeMillis()-start);
		
		start=System.currentTimeMillis();
		String s3="";
		for (int i = 0; i < TIMES3; i++) {
			s3+=STRING;
		}
		System.out.println(System.currentTimeMillis()-start);
		
		start=System.currentTimeMillis();
		StringBuilder sbd3=new StringBuilder();
		for (int i = 0; i < TIMES3; i++) {
			sbd3.append(STRING);
		}
		System.out.println(System.currentTimeMillis()-start);
	}
}



以前还真没仔细比较过两者的效率差距,今天闲来写个比较垃圾的测试类看看结果,很吃惊啊
具体两者比较就不多说了,看结果
16
0
984
0
401094
16

你可能感兴趣的:(StringBuilder)