Java字符串拼接三种方式比较

Java中提供了三种字符串拼接的方法:+、concat()以及append()方法。通过比较 append()速度最快,concat()次之,+ 最慢。原因请看下面分析:

+ 方式拼接字符串
编译器对+进行了优化,它是使用StringBuilder的append()方法来进行处理的,编译器使用append()方法追加后要同toString()转换成String字符串,也就说 str +=”b”等同于str = new StringBuilder(str).append(“b”).toString();
它变慢的关键原因就在于new StringBuilder()和toString()

concat()方法拼接字符串

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

这是concat()的源码,它看上去就是一个数字拷贝形式,我们知道数组的处理速度是非常快的,但是由于该方法最后是这样的:return new String(0, count + otherLen, buf);这是它变慢的根本原因。

append()方法拼接字符串

public AbstractStringBuilder append(String str) {
    if (str == null) str = "null";
        int len = str.length();
    if (len == 0) return this;
    int newCount = count + len;
    if (newCount > value.length)
        expandCapacity(newCount);
    str.getChars(0, len, value, count);
    count = newCount;
    return this;
}

这是append()的源码,StringBuffer的append()方法是直接使用父类AbstractStringBuilder的append()方法。
与concat()方法相似,它也是进行字符数组处理的,加长,然后拷贝,但它最后是返回并没有返回一个新串,而是返回本身。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值