java五种拼接字符串的方法
package test; import org.apache.commons.lang.StringUtils; public class CutString { //性能最差 public String testPlus() { String s = ""; for (int i = 0; i < 10000; i++) { s = s + String.valueOf(i); } return s; } //较好 public String testConcat() { String s = ""; for (int i = 0; i < 10000; i++) { s = s.concat(String.valueOf(i)); } return s; } //性能与testStringBuffer相差无几,比其要好 public String testJoin() { String[] list = new String[10000]; for (int i = 0; i < 10000; i++) { list[i] = String.valueOf(i); } return StringUtils.join(list, ""); } public String testStringBuffer() { StringBuffer sb = new StringBuffer(); long l1 = System.currentTimeMillis(); for (int i = 0; i < 10000; i++) { sb.append(String.valueOf(i)); } long l2 = System.currentTimeMillis(); System.out.println(l2-l1); return sb.toString(); } //性能最高的方法 public void testStringBuilder() { StringBuilder sb = new StringBuilder(); for (int i = 0; i < 100000; i++) { sb.append(String.valueOf(i)); } sb.toString(); } public static void main(String[] args) { System.out.println(new CutString().testStringBuffer()); } }