String、StringBuilder、StringBuffer 用法比较

简介: 【本文转载于http://blog.csdn.net/ithomer/article/details/7669843】 String、StringBuilder、StringBuffer 三个类源自JDK的 java/lang/ 目录下: String 字符串常量StringBuffer 字符串变量(线程安全)StringBuilder 字符串变量(非线程安全,JDK 5.0(1.

【本文转载于http://blog.csdn.net/ithomer/article/details/7669843】

String、StringBuilder、StringBuffer 三个类源自JDK的 java/lang/ 目录下:

String 字符串常量
StringBuffer 字符串变量(线程安全)
StringBuilder 字符串变量(非线程安全,JDK 5.0(1.5.0) 后支持)

String
 简要的说, String 类型和 StringBuffer 类型的主要性能区别其实在于 String 是不可变的对象, 因此在每次对 String 类型进行改变的时候其实都等同于生成了一个新的 String 对象,然后将指针指向新的 String 对象,所以经常改变内容的字符串最好不要用 String ,因为每次生成对象都会对系统性能产生影响,特别当内存中无引用对象多了以后, JVM 的 GC 就会开始工作,那速度是一定会相当慢的。

String 构造函数:

[java]  view plain copy print ?
  1. private final char value[];  
  2.    private final int offset;  
  3.    private final int count;  
  4.   
  5. public String() {  
  6.        this.offset = 0;  
  7.        this.count = 0;  
  8.        this.value = new char[0];  
  9.    }  
  10.   
  11. public String(String original) {  
  12.        int size = original.count;  
  13.        char[] originalValue = original.value;  
  14.        char[] v;  
  15.        if (originalValue.length > size) {  
  16.            // The array representing the String is bigger than the new  
  17.            // String itself.  Perhaps this constructor is being called  
  18.            // in order to trim the baggage, so make a copy of the array.  
  19.            int off = original.offset;  
  20.            v = Arrays.copyOfRange(originalValue, off, off+size);  
  21.        } else {  
  22.            // The array representing the String is the same  
  23.            // size as the String, so no point in making a copy.  
  24.            v = originalValue;  
  25.        }  
  26.        this.offset = 0;  
  27.        this.count = size;  
  28.        this.value = v;  
  29.    }  
  30.   
  31. public String(char value[]) {  
  32.        int size = value.length;  
  33.        this.offset = 0;  
  34.        this.count = size;  
  35.        this.value = Arrays.copyOf(value, size);  
  36.    }  
  37.   
  38. public String(char value[], int offset, int count) {  
  39.        if (offset < 0) {  
  40.            throw new StringIndexOutOfBoundsException(offset);  
  41.        }  
  42.        if (count < 0) {  
  43.            throw new StringIndexOutOfBoundsException(count);  
  44.        }  
  45.        // Note: offset or count might be near -1>>>1.  
  46.        if (offset > value.length - count) {  
  47.            throw new StringIndexOutOfBoundsException(offset + count);  
  48.        }  
  49.        this.offset = 0;  
  50.        this.count = count;  
  51.        this.value = Arrays.copyOfRange(value, offset, offset+count);  
  52.    }  
  53.   
  54. public String substring(int beginIndex, int endIndex) {  
  55.        if (beginIndex < 0) {  
  56.            throw new StringIndexOutOfBoundsException(beginIndex);  
  57.        }  
  58.        if (endIndex > count) {  
  59.            throw new StringIndexOutOfBoundsException(endIndex);  
  60.        }  
  61.        if (beginIndex > endIndex) {  
  62.            throw new StringIndexOutOfBoundsException(endIndex - beginIndex);  
  63.        }  
  64.        return ((beginIndex == 0) && (endIndex == count)) ? this :  
  65.            new String(offset + beginIndex, endIndex - beginIndex, value);       // 返回新对象  
  66.    }  
  67.   
  68. public String concat(String str) {  
  69.        int otherLen = str.length();  
  70.        if (otherLen == 0) {  
  71.            return this;  
  72.        }  
  73.        char buf[] = new char[count + otherLen];  
  74.        getChars(0, count, buf, 0);  
  75.        str.getChars(0, otherLen, buf, count);  
  76.        return new String(0, count + otherLen, buf);     // 返回新对象  
  77.    }  
  78.   
  79. public static String valueOf(char data[]) {  
  80.        return new String(data);     // 返回新对象  
  81.    }  
  82.   
  83. public static String valueOf(char c) {  
  84.        char data[] = {c};  
  85.        return new String(01, data);       // 返回新对象  
  86.    }  

StringBuffer
StringBuffer 每次对对象本身进行操作,而不是生成新的对象,再改变对象引用。所以在一般情况下我们推荐使用 StringBuffer ,特别是字符串对象经常改变的情况下。

StringBuffer 构造函数:

[java]  view plain copy print ?
  1. public StringBuffer() {  
  2.        super(16);  
  3.    }  
  4.   
  5. public StringBuffer(int capacity) {  
  6.        super(capacity);  
  7.    }  
  8.   
  9. public StringBuffer(String str) {  
  10.        super(str.length() + 16);  
  11.        append(str);  
  12.    }  
  13.   
  14. public StringBuffer(CharSequence seq) {  
  15.        this(seq.length() + 16);  
  16.        append(seq);  
  17.    }  
  18.   
  19. public synchronized int length() {      // 字节实际长度  
  20.        return count;  
  21.    }  
  22.   
  23. public synchronized int capacity() {    // 字节存储容量(value数组的长度)  
  24.        return value.length;  
  25.    }  
  26.   
  27. public synchronized void ensureCapacity(int minimumCapacity) {  
  28.        if (minimumCapacity > value.length) {  
  29.            expandCapacity(minimumCapacity);  
  30.        }  
  31.    }  
  32.   
  33. public synchronized StringBuffer append(Object obj) {  
  34.        super.append(String.valueOf(obj));  
  35.        return this// 返回对象本身  
  36.    }  
  37.   
  38. public synchronized StringBuffer append(String str) {  
  39.        super.append(str);  
  40.        return this// 返回对象本身  
  41.    }  
  42.   
  43. public synchronized StringBuffer append(StringBuffer sb) {  
  44.        super.append(sb);  
  45.        return this// 返回对象本身  
  46.    }  


而在某些特别情况下, String 对象的字符串拼接其实是被 JVM 解释成了 StringBuffer 对象的拼接,所以这些时候 String 对象的速度并不会比 StringBuffer 对象慢,而特别是以下的字符串对象生成中, String 效率是远要比 StringBuffer 快的:
 String S1 = “This is only a” + “ simple” + “ test”;
 StringBuffer Sb = new StringBuilder(“This is only a”).append(“ simple”).append(“ test”);

 你会很惊讶的发现,生成 String S1 对象的速度简直太快了,而这个时候 StringBuffer 居然速度上根本一点都不占优势。其实这是 JVM 的一个把戏,在 JVM 眼里,这个
 String S1 = “This is only a” + “ simple” + “test”; 

其实就是:
 String S1 = “This is only a simple test”; 

所以当然不需要太多的时间了。但大家这里要注意的是,如果你的字符串是来自另外的 String 对象的话,速度就没那么快了,譬如:
String S2 = “This is only a”;
String S3 = “ simple”;
String S4 = “ test”;
String S1 = S2 +S3 + S4;

这时候 JVM 会规规矩矩的按照原来的方式去做

在大部分情况下: StringBuffer > String

Java.lang.StringBuffer线程安全的可变字符序列。一个类似于 String 的字符串缓冲区,但不能修改。虽然在任意时间点上它都包含某种特定的字符序列,但通过某些方法调用可以改变该序列的长度和内容。
可将字符串缓冲区安全地用于多个线程。可以在必要时对这些方法进行同步,因此任意特定实例上的所有操作就好像是以串行顺序发生的,该顺序与所涉及的每个线程进行的方法调用顺序一致。
StringBuffer 上的主要操作是 append 和 insert 方法,可重载这些方法,以接受任意类型的数据。每个方法都能有效地将给定的数据转换成字符串,然后将该字符串的字符追加或插入到字符串缓冲区中。append 方法始终将这些字符添加到缓冲区的末端;而 insert 方法则在指定的点添加字符。
例如,如果 z 引用一个当前内容是“start”的字符串缓冲区对象,则此方法调用 z.append("le") 会使字符串缓冲区包含“startle”,而 z.insert(4, "le") 将更改字符串缓冲区,使之包含“starlet”。

StringBuilder
java.lang.StringBuilder一个可变的字符序列是5.0新增的。此类提供一个与 StringBuffer 兼容的 API,但不同步。该类被设计用作 StringBuffer 的一个简易替换,用在字符串缓冲区被单个线程使用的时候(这种情况很普遍)。如果可能,建议优先采用该类,因为在大多数实现中,它比 StringBuffer 要快。两者的方法基本相同。

StringBuilder 构造函数:

[java]  view plain copy print ?
  1. public StringBuilder() {  
  2.        super(16);  
  3.    }  
  4.   
  5. public StringBuilder(int capacity) {  
  6.        super(capacity);  
  7.    }  
  8.   
  9. public StringBuilder(String str) {  
  10.        super(str.length() + 16);  
  11.        append(str);  
  12.    }  
  13.   
  14. public StringBuilder(CharSequence seq) {  
  15.        this(seq.length() + 16);  
  16.        append(seq);  
  17.    }  
  18.   
  19. public StringBuilder append(Object obj) {  
  20.        return append(String.valueOf(obj));  
  21.    }  
  22.   
  23.    public StringBuilder append(String str) {  
  24.        super.append(str);  
  25.        return this// 返回对象本身  
  26.    }  
  27.   
  28. private StringBuilder append(StringBuilder sb) {  
  29.        if (sb == null)  
  30.            return append("null");  
  31.        int len = sb.length();  
  32.        int newcount = count + len;  
  33.        if (newcount > value.length)  
  34.            expandCapacity(newcount);  
  35.        sb.getChars(0, len, value, count);  
  36.        count = newcount;  
  37.        return this// 返回对象本身  
  38.    }  
  39.   
  40. public StringBuilder append(StringBuffer sb) {  
  41.        super.append(sb);  
  42.        return this// 返回对象本身  
  43.    }  

在大部分情况下: StringBuilder > StringBuffer


总结

StringBuffer 和 StringBuilder 都继承于 AbstractStringBuilder 父类,实现了java.io.Serializable, CharSequence

AbstractStringBuilder 父类构造函数:

[java]  view plain copy print ?
  1. char[] value;       // 字符数组  
  2.   
  3. AbstractStringBuilder() {  
  4.    }  
  5.   
  6. AbstractStringBuilder(int capacity) {  
  7.        value = new char[capacity];      // 申请字节存储容量  
  8.    }  
  9.   
  10. public int length() {  
  11.        return count;            // 返回实际字节长度  
  12.    }  
  13.   
  14. public int capacity() {  
  15.        return value.length; // 返回字节存储容量  
  16.    }  
  17.   
  18. public void ensureCapacity(int minimumCapacity) {  
  19.        if (minimumCapacity > 0)  
  20.            ensureCapacityInternal(minimumCapacity); // 扩展容量大小  
  21.    }  
  22.   
  23. private void ensureCapacityInternal(int minimumCapacity) {  
  24.        // overflow-conscious code  
  25.        if (minimumCapacity - value.length > 0)       // 如果设置的最小容量 > 当前字节存储容量  
  26.            expandCapacity(minimumCapacity);  
  27.    }  
  28.   
  29. void expandCapacity(int minimumCapacity) {  
  30.        int newCapacity = value.length * 2 + 2;      // 自动新增容量,为当前容量的2倍加2(java是unicode编码,占两个字节)  
  31.        if (newCapacity - minimumCapacity < 0)  
  32.            newCapacity = minimumCapacity;  
  33.        if (newCapacity < 0) {  
  34.            if (minimumCapacity < 0// overflow  
  35.                throw new OutOfMemoryError();  
  36.            newCapacity = Integer.MAX_VALUE;  
  37.        }  
  38.        value = Arrays.copyOf(value, newCapacity);  
  39.    }  
  40.   
  41. public AbstractStringBuilder append(Object obj) {  
  42.        return append(String.valueOf(obj));  
  43.    }  
  44.   
  45. public AbstractStringBuilder append(String str) {  
  46.        if (str == null) str = "null";  
  47.        int len = str.length();  
  48.        ensureCapacityInternal(count + len);  
  49.        str.getChars(0, len, value, count);  
  50.        count += len;  
  51.        return this;     // 返回对象本身  
  52.    }  
  53.   
  54. public AbstractStringBuilder append(StringBuffer sb) {  
  55.        if (sb == null)  
  56.            return append("null");  
  57.        int len = sb.length();  
  58.        ensureCapacityInternal(count + len);  
  59.        sb.getChars(0, len, value, count);  
  60.        count += len;  
  61.        return this;     // 返回对象本身  
  62.    }  
  63.   
  64. public AbstractStringBuilder append(CharSequence s) {  
  65.        if (s == null)  
  66.            s = "null";  
  67.        if (s instanceof String)  
  68.            return this.append((String)s);  
  69.        if (s instanceof StringBuffer)  
  70.            return this.append((StringBuffer)s);  
  71.        return this.append(s, 0, s.length());        // 返回对象本身  
  72.    }  

关于String更多的介绍,请详见我先前写的博客:Java 之 String 类型

在大部分情况下,三者的效率如下:

StringBuilde > StringBuffer > String

目录
相关文章
|
1月前
|
安全 Java
Java StringBuffer 和 StringBuilder 类
Java StringBuffer 和 StringBuilder 类
16 0
|
1月前
|
编译器 容器
C++string类的介绍及常用函数用法总结
C++string类的介绍及常用函数用法总结
29 1
|
2天前
|
存储 编解码 算法
Java 的 String StringBuilder StringBuffer(上)
Java 的 String StringBuilder StringBuffer
24 0
|
17天前
|
移动开发 安全 Java
String、StringBuffer 、StringBuilder、StringJoiner
String、StringBuffer 、StringBuilder、StringJoiner
|
1月前
|
存储 算法 安全
【数据结构与算法初学者指南】【冲击蓝桥篇】String与StringBuilder的区别和用法
【数据结构与算法初学者指南】【冲击蓝桥篇】String与StringBuilder的区别和用法
|
16天前
|
Java API 索引
Java基础—笔记—String篇
本文介绍了Java中的`String`类、包的管理和API文档的使用。包用于分类管理Java程序,同包下类无需导包,不同包需导入。使用API时,可按类名搜索、查看包、介绍、构造器和方法。方法命名能暗示其功能,注意参数和返回值。`String`创建有两种方式:双引号创建(常量池,共享)和构造器`new`(每次新建对象)。此外,列举了`String`的常用方法,如`length()`、`charAt()`、`equals()`、`substring()`等。
15 0
|
1月前
|
Java
【Java】如果一个集合中类型是String如何使用拉姆达表达式 进行Bigdecimal类型计算?
【Java】如果一个集合中类型是String如何使用拉姆达表达式 进行Bigdecimal类型计算?
25 0
|
1月前
|
Java
Java String split()方法详细教程
Java String split()方法详细教程
23 0
|
1月前
|
存储 缓存 安全
【Java】Java中String不可变性的底层实现
【Java】Java中String不可变性的底层实现
16 0
|
1月前
|
Java 索引
Java中String方法学习总结_kaic
Java中String方法学习总结_kaic