字符串进行拼接有三种方法:加号、contact方法和StringBufferStringBuilder,StringBufferStringBuilder拼接方法相似,只是StringBuilder用于单线程,StringBuffer是线程安全的,用于多线程。

主要探讨一下以上三种拼接方法的效率,当然大概效率都是知道的,如下

StringBuffer>concat>”>”

虽然知道这个结果,但是也更得知道所以然。

1.+”方法拼接字符串

虽然编译器对字符串的加号做了优化,它会使用StringBuilderappend方法进行追加,那么按道理来说,它的执行时间也应该和StringBuilder差不多啊,但是不然,实际实现如下:

Str=new StringBuilder(str).append(“c”).toString();

它每次拼接都会创建一个StringBuilder对象,并且还要调用toString()方法将其转换为字符串,这样性能就大大降低了。

2.concat方法拼接字符串

首先看下源码:

public String concat(String str){
        int otherLen = str.length();
        //如果追加的字符串长度为0,则返回字符串本身
        if(otherLen == 0){
            return this;
        }
        //字符数组,容纳的是新字符串的字符
        char buf[] = new char[count + otherLen];
        //取出原始字符串放到buf数组中
        getChars(0, count, buf, 0);
        //追加的字符串转换成字符数组,添加到buf中
        str.getChars(0, otherLen, buf, count);
        //复制字符数组,产生一个新的字符串
        return new String(0, count + otherLen, buf);
    }
        



整体上看上去就是一个数组拷贝,虽然在内存中的处理都是原子性操作,速度非常快,但是最后一句return,每次的concat操作都会创建一个String对象,这样就会让concat的速度慢下来。

3.StringBuilder.append()方法拼接

源码如下:

public AbstractStringBuilder append(String str){
        //如果为null值,则把null作为字符串处理
        if(str==null) str = "null";
        int len = str.length();
        //字符长度为0,则返回本身
        if(len == 0) return this;
        int newCount = count +len;
        //追加后的字符数组长度是否超过当前值
        if(newCount > value.length()){
            //加长,并做数组拷贝
            expanCapacity(newCount);
        }
        //字符串复制到目标数组
        str.getChars(0, len, value, count);
        count = newCount;
        return this;
    }



整个append方法都在做字符数组处理,加长,然后数组拷贝,这些都是基本的数据处理,没有创建任何对象,所以速度是非常快的。