System.currentTimeMillis();
//当前时间与1970年1月1日午夜UTC之间的毫秒差。
public class HelloWorld {
public static void main(String[] args) {
String s1 = "";
StringBuilder s2 = new StringBuilder("");
long time = System.currentTimeMillis();
long spendTime;
int n = 100000;
for (int i = 0; i < n; i++) {
s1 += "abc";
}
spendTime = System.currentTimeMillis()-time;
System.out.println(spendTime/1000.0 + "s");//String操作花费的时间
time = System.currentTimeMillis();
for (int i = 0; i < n; i++) {
s2.append("abc");
}
spendTime = System.currentTimeMillis()-time;
System.out.println(spendTime/1000.0 + "s");//StringBuilder操作花费的时间
}
}
StringBuilder明显快于String。