Java| String 字符串拼接方法 concat 和 + 效率比较

时间:2025-02-21 07:27:12

测试代码:

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

总结:

  • 的计算效率要比+的效率高
  • 只适用于string和string的拼接,+适用于string和任何对象的拼接
  • 3.当在少量的数据拼接时,使用concat和+都行,如果是大量的数据拼接,建议使用StringBuilder或者StringBuffer.