龙哥网

龙哥网

String字符串拼接方法concat和+的效率对比_java
2022-03-01

目录
  • 两个方法效率计算代码如下
  • 多次测试结果如下
  • 字符串拼接 和concat的区别

两个方法效率计算代码如下

public static void main(String[] args) {
    String s1 = "a";
    String str1="";
    String str2="";
    /**
     * 计算concat所用时间
     */
    long str1Start = System.currentTimeMillis();
    for (int i=0;i<10000;i++){
        str1=str1.concat(s1);
    }
    long str1End = System.currentTimeMillis();
    System.out.println("concat计算时间为:" + (str1End - str1Start));
    /**
     * 计算+所用时间
     */
    long str2Start = System.currentTimeMillis();
    for (int i=0;i<10000;i++){
        str2=str2+s1;
    }
    long str2End = System.currentTimeMillis();
    System.out.println("+计算时间为:" + (str2End - str2Start));
}

多次测试结果如下

经计算平均值为:

contact:45.75

+:123.75

结论为:

  • concat的计算效率要比+的效率高
  • concat只适用于string和string的拼接,+适用于string和任何的拼接

字符串拼接 和concat的区别

+和concat都可以用来拼接字符串,但在使用上有什么区别呢,先来看看这个例子。

public static void main(String[] args) {
    // example1
    String str1 = "s1";
    System.out.println(str1 + 100);//s1100
    System.out.println(100 + str1);//100s1
 
    String str2 = "s2";
    str2 = str2.concat("a").concat("bc");
    System.out.println(str2);//s2abc
 
    // example2
    String str3 = "s3";
    System.out.println(str3 + null);//s3null
    System.out.println(null + str3);//nulls3
 
    String str4 = null;
    System.out.println(str4.concat("a"));//NullPointerException
    System.out.println("a".concat(str4));//NullPointerException
}

concat源码:

public String concat(String str) {
    int otherLen = str.length();
    if (otherLen == 0) {
        return this;
    }
    int len = value.length;
    char buf[] = Arrays.copyOf(value, len + otherLen);
    str.getChars(buf, len);
    return new String(buf, true);
}

看下生成的字节码:

所以可以得出以下结论:

  • +可以是字符串或者数字及其他基本类型数据,而concat只能接收字符串。
  • +左右可以为null,concat为会空指针。

如果拼接空字符串,concat会稍快,在速度上两者可以忽略不计,如果拼接更多字符串建议用StringBuilder。

从字节码来看+号编译后就是使用了StringBuiler来拼接,所以一行+++的语句就会创建一个StringBuilder,多条+++语句就会创建多个,所以为什么建议用StringBuilder的原因。

免责声明
本站部分资源来源于互联网 如有侵权 请联系站长删除
龙哥网是优质的互联网科技创业资源_行业项目分享_网络知识引流变现方法的平台为广大网友提供学习互联网相关知识_内容变现的方法。