测试String与StringBuffer的性能区别
先使用String连接1000000个字符串,计算消耗的时间 ++
再使用StringBuffer连接1000000个字符串,计算各自消耗的时间
对比在大量字符串内容拼接的性能.
public static void main(String[] args) {
String s = "";
Date date = new Date();
long a = date.getTime();
System.out.println(a);
for (int i = 0; i <100000 ; i++) {
s+="A";
}
Date date1 = new Date();
long a1 = date1.getTime();
System.out.println(a1);
System.out.println(a1-a);
StringBuffer s1 = new StringBuffer();
long a2 = new Date().getTime();
System.out.println(a2);
for (int i = 0; i < 100000; i++) {
s1.append("A");
}
long a3 = new Date().getTime();
System.out.println(a3);
System.out.println(a3-a2);
}
以上代码可以明显的观察出String与StringBuffer的性能区别
尤其在拼接大量的字符串上尤为明显