String字符串拼接效率比较

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

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

StringBuffer>concat>”>”安全

虽然知道这个结果,可是也更得知道因此然。多线程

1.+”方法拼接字符串app

虽然编译器对字符串的加号作了优化,它会使用StringBuilderappend方法进行追加,那么按道理来讲,它的执行时间也应该和StringBuilder差很少啊,可是否则,实际实现以下:ide

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

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

2.concat方法拼接字符串优化

首先看下源码:ui

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的速度慢下来。this

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方法都在作字符数组处理,加长,而后数组拷贝,这些都是基本的数据处理,没有建立任何对象,因此速度是很是快的。

相关文章
相关标签/搜索