以下代码转载自其他博客
public class StringTest {
/**
* @desc 使用+、concat()、append()方法循环10W次
* @author chenssy
* @data 2013-11-16
* @param args
* @return void
*/
public static void main(String[] args) {
long start_01 = System.currentTimeMillis();
String a = "a";
for (int i = 0; i < 100000; i++) {
a += "b";
}
long end_01 = System.currentTimeMillis();
System.out.println(" + 所消耗的时间:" + (end_01 - start_01) + "毫秒");
//concat()
long start_02 = System.currentTimeMillis();
String c = "c";
for (int i = 0; i < 100000; i++) {
c = c.concat("d");
}
long end_02 = System.currentTimeMillis();
System.out.println("concat所消耗的时间:" + (end_02 - start_02) + "毫秒");
//append
long start_03 = System.currentTimeMillis();
StringBuilder e = new StringBuilder("e");
for (int i = 0; i < 100000; i++) {
e.append("d");
}
long end_03 = System.currentTimeMillis();
System.out.println("StringBuilder所消耗的时间:" + (end_03 - start_03) + "毫秒");
long start_04 = System.currentTimeMillis();
StringBuffer f = new StringBuffer("f");
for (int i = 0; i < 100000; i++) {
f.append("g");
}
long end_04 = System.currentTimeMillis();
System.out.println("StringBuffer所消耗的时间:" + (end_04 - start_04) + "毫秒");
}
运行结果
+ 所消耗的时间:9095毫秒
concat所消耗的时间:3040毫秒
StringBuilder所消耗的时间:1毫秒
StringBuffer所消耗的时间:4毫秒