对采用+、concat、StringBuffer、StringBuilder的连接效率问题,做了一个简单的测试
public class TestTime {
public static void main(String[] args) {
String s = "0";
long startTime = System.currentTimeMillis();
for ( int i = 0; i < 50000; i++) {
s+="0";
}
long endTime = System.currentTimeMillis();
System.out.println("'+'号连接测试(50000个'0'连接)");
System.out.println((endTime - startTime)+"ms");
//---------------------------------------------------------------------------
s = "0";
startTime = System.currentTimeMillis();
for ( int i = 0; i < 50000; i++) {
s=s.concat("0");
}
endTime = System.currentTimeMillis();
System.out.println("concat测试(50000个'0'连接)");
System.out.println((endTime - startTime)+"ms");
//---------------------------------------------------------------------------
StringBuffer sb = new StringBuffer("0");
startTime = System.currentTimeMillis();
for ( int i = 0; i < 5000000; i++) {
sb.append("0");
}
endTime = System.currentTimeMillis();
System.out.println("StringBuffer连接测试(5000000个'0'连接)");
System.out.println((endTime - startTime)+"ms");
//---------------------------------------------------------------------------
StringBuilder sb2 = new StringBuilder("0");
startTime = System.currentTimeMillis();
for ( int i = 0; i < 5000000; i++) {
sb2.append("0");
}
endTime = System.currentTimeMillis();
System.out.println("StringBuiler连接测试(5000000个'0'连接)");
System.out.println((endTime - startTime)+"ms");
}
}