String、StringBuffer和StringBuilder

    String

       String是一种引用数据类型,对String对象的任何操作不会影响原对象,都会重新创建新对象;这一点由String类的源码可以看出来:

public String substring(int beginIndex, int endIndex) {
    if (beginIndex < 0) {
        throw new StringIndexOutOfBoundsException(beginIndex);
    }
    if (endIndex > count) {
        throw new StringIndexOutOfBoundsException(endIndex);
    }
    if (beginIndex > endIndex) {
        throw new StringIndexOutOfBoundsException(endIndex - beginIndex);
    }
    return ((beginIndex == 0) && (endIndex == count)) ? this :
        new String(offset + beginIndex, endIndex - beginIndex, value);
    }
 
 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);
    }
 
 public String replace(char oldChar, char newChar) {
    if (oldChar != newChar) {
        int len = count;
        int i = -1;
        char[] val = value; /* avoid getfield opcode */
        int off = offset;   /* avoid getfield opcode */
 
        while (++i < len) {
        if (val[off + i] == oldChar) {
            break;
        }
        }
        if (i < len) {
        char buf[] = new char[len];
        for (int j = 0 ; j < i ; j++) {
            buf[j] = val[off+j];
        }
        while (i < len) {
            char c = val[off + i];
            buf[i] = (c == oldChar) ? newChar : c;
            i++;
        }
        return new String(0, len, buf);
        }
    }

    无论是哪种操作,最后都会重新new一个新的字符串对象。

    StringBuilder

       StringBuilder的append操作,都是在原对象基础上进行改变,即减少内存中new操作的次数,对于多字符串拼接,处理效率提升很多。

public class Test {
    
    public static void main(String[] args) {
        long startTime1=System.currentTimeMillis();//记录循环开始之前时间戳
            String str1 = "";
            for(int i=0;i<1000;i++){
                str1 += "hello";
            }
        long endTime1=System.currentTimeMillis();//记录循环完成之后时间戳
        System.out.println("String直接拼接总耗时:"+(endTime1-startTime1)+"毫秒");//计算循环总耗时
        
        
        long startTime2=System.currentTimeMillis();//记录循环开始之前时间戳
            StringBuilder sb=new StringBuilder();
            for(int i=0;i<1000;i++){
                sb.append("hello");
            }
        long endTime2=System.currentTimeMillis();//记录循环完成之后时间戳
        System.out.println("StringBuilder拼接总耗时:"+(endTime2-startTime2)+"毫秒");//计算循环总耗时
       
    }
}

运行结果如下:

  

 

    StringBuffer:

       StringBuffer跟StringBuilder类的成员方法基本上差不多,唯一的区别是每个方法上多了一个Synchronized关键字,即StringBuffer是线程安全的。拼接效率基本和StringBuilder差不多。在非多线程环境下,StringBuffer和StringBuilder可以随意选用。在多线程环境下,选用StringBuffer。

posted @ 2019-01-31 10:53  正直的不良帅  Views(167)  Comments(0)    收藏  举报