测试代码:
public static void main(String[] args) { String str1 = "yveshe"; String str2 = "hello"; /** * concat */ System.gc(); long startTime1 = System.currentTimeMillis(); for (int i = 0; i < 10000; i++) { str1 = str1.concat(str2); } long endTime1 = System.currentTimeMillis(); System.out.println("concat:" + (endTime1 - startTime1)); /** * + */ str1 = "yveshe"; System.gc(); long startTime2 = System.currentTimeMillis(); for (int i = 0; i < 10000; i++) { str1 = str1 + str2; } long endTime2 = System.currentTimeMillis(); System.out.println("+: " + (endTime2 - startTime2)); }测试结果:
concat:231 +: 468总结:
1.concat的计算效率要比+的效率高2.concat只适用于string和string的拼接,+适用于string和任何对象的拼接3.当在少量的数据拼接时,使用concat和+都行,如果是大量的数据拼接,建议使用StringBuilder或者StringBuffer.