Java 中字符串拼接 String 和 StringBuilder(StringBuffer)的使用
字符串拼接是個常用的功能,經(jīng)常性使用String做字符串拼接,當拼接次數(shù)多的時候,使用String方法會消耗大量的性能和時間,因為每次String拼接時都會建立一個新的對象,隨著拼接次數(shù)的增多,性能消耗、時間消耗會大量增加,這個時候應(yīng)該使用StringBuilder方法。
public static void main(String[] args) {
try {
int count = 500;
long begin = System.currentTimeMillis();
testString(count);
long end = System.currentTimeMillis();
long time = end - begin;
System.out.println("String 方法拼接"+count+"次消耗時間:" + time + "毫秒");
begin = System.currentTimeMillis();
testStringBuilder(count);
end = System.currentTimeMillis();
time = end - begin;
System.out.println("StringBuilder 方法拼接"+count+"次消耗時間:" + time + "毫秒");
} catch (Exception e) {
e.printStackTrace();
}
}
private static String testString(int count) {
String result = "";
for (int i = 0; i < count; i++) {
result += "hello ";
}
return result;
}
private static String testStringBuilder(int count) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < count; i++) {
sb.append("hello");
}
return sb.toString();
}
運行結(jié)果:
String 方法拼接500次消耗時間:2毫秒 StringBuilder 方法拼接500次消耗時間:0毫秒
String 方法拼接50000次消耗時間:4973毫秒 StringBuilder 方法拼接50000次消耗時間:3毫秒