在for循环中字符串拼接一般使用StringBuffer.append()来代替String的运算符+

每次循环里的字符串+连接,都会新产生一个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();


猜你喜欢

转载自blog.csdn.net/ydk888888/article/details/80109339