static void testString(){
String sf = "abcdefghijklmnopqrstuvwxyz";
int tick = 10000;
long startTime = System.currentTimeMillis();
String str1 ="";
for (int i = 0; i < tick;i++){
str1 += sf;
System.out.println("string:" + (endTime - startTime) + "ms");
String sf = "abcdefghijklmnopqrstuvwxyz";
int tick = 10000;
long startTime = System.currentTimeMillis();
String str1 ="";
for (int i = 0; i < tick;i++){
str1 += sf;
}
System.out.println("string:" + (endTime - startTime) + "ms");
}
static void testStringBuffer(){
StringBuffer sfbBuffer = new StringBuffer("abcdefghijklmnopqrstuvwxyz");
int tick = 10000;
long startTime = System.currentTimeMillis();
StringBuffer str1 = new StringBuffer();
for (int i = 0; i < tick;i++){
str1.append(sfbBuffer);
}
long endTime = System.currentTimeMillis();
System.out.println("stringBuffer:" + (endTime - startTime) + "ms");
}
运行二次结果
string:3042ms
stringBuffer:5ms
string:3238ms
stringBuffer:5ms
当操作量大的时候stringBuffer的性能优势就显示出来了