每次循环里的字符串+连接,都会新产生一个string对象,在java中,新建一个对象的代价是很昂贵的,特别是在循环语句中,效率较低。故在循环中一般使用StringBuffer.append来代替string的+运算符
// This is bad
String s = "";
for (int i = 0; i < field.length; ++i) {
s = s + field[i];
}
// This is better
StringBuffer buf = new StringBuffer();for (int i = 0; i < field.length; ++i) {
buf.append(field[i]);
}
String s = buf.toString();