天天看点

String、StringBuilder、StringBuffer 用法比较

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

string

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

private final char value[];  

   private final int offset;  

   private final int count;  

public string() {  

       this.offset = 0;  

       this.count = 0;  

       this.value = new char[0];  

   }  

public string(string original) {  

       int size = original.count;  

       char[] originalvalue = original.value;  

       char[] v;  

       if (originalvalue.length > size) {  

           // the array representing the string is bigger than the new  

           // string itself.  perhaps this constructor is being called  

           // in order to trim the baggage, so make a copy of the array.  

           int off = original.offset;  

           v = arrays.copyofrange(originalvalue, off, off+size);  

       } else {  

           // the array representing the string is the same  

           // size as the string, so no point in making a copy.  

           v = originalvalue;  

       }  

       this.count = size;  

       this.value = v;  

public string(char value[]) {  

       int size = value.length;  

       this.value = arrays.copyof(value, size);  

public string(char value[], int offset, int count) {  

       if (offset < 0) {  

           throw new stringindexoutofboundsexception(offset);  

       if (count < 0) {  

           throw new stringindexoutofboundsexception(count);  

       // note: offset or count might be near -1>>>1.  

       if (offset > value.length - count) {  

           throw new stringindexoutofboundsexception(offset + count);  

       this.count = count;  

       this.value = arrays.copyofrange(value, offset, offset+count);  

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 static string valueof(char data[]) {  

       return new string(data);     // 返回新对象  

public static string valueof(char c) {  

       char data[] = {c};  

       return new string(0, 1, data);       // 返回新对象  

stringbuffer

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

public stringbuffer() {  

       super(16);  

public stringbuffer(int capacity) {  

       super(capacity);  

public stringbuffer(string str) {  

       super(str.length() + 16);  

       append(str);  

public stringbuffer(charsequence seq) {  

       this(seq.length() + 16);  

       append(seq);  

public synchronized int length() {      // 字节实际长度  

       return count;  

public synchronized int capacity() {    // 字节存储容量(value数组的长度)  

       return value.length;  

public synchronized void ensurecapacity(int minimumcapacity) {  

       if (minimumcapacity > value.length) {  

           expandcapacity(minimumcapacity);  

public synchronized stringbuffer append(object obj) {  

       super.append(string.valueof(obj));  

       return this; // 返回对象本身  

public synchronized stringbuffer append(string str) {  

       super.append(str);  

public synchronized stringbuffer append(stringbuffer sb) {  

       super.append(sb);  

而在某些特别情况下, 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 要快。两者的方法基本相同。

public stringbuilder() {  

public stringbuilder(int capacity) {  

public stringbuilder(string str) {  

public stringbuilder(charsequence seq) {  

public stringbuilder append(object obj) {  

       return append(string.valueof(obj));  

   public stringbuilder append(string str) {  

private stringbuilder append(stringbuilder sb) {  

       if (sb == null)  

           return append("null");  

       int len = sb.length();  

       int newcount = count + len;  

       if (newcount > value.length)  

           expandcapacity(newcount);  

       sb.getchars(0, len, value, count);  

       count = newcount;  

public stringbuilder append(stringbuffer sb) {  

在大部分情况下: stringbuilder > stringbuffer

总结

stringbuffer 和 stringbuilder 都继承于 abstractstringbuilder 父类,实现了java.io.serializable, charsequence

char[] value;       // 字符数组  

abstractstringbuilder() {  

abstractstringbuilder(int capacity) {  

       value = new char[capacity];      // 申请字节存储容量  

public int length() {  

       return count;            // 返回实际字节长度  

public int capacity() {  

       return value.length; // 返回字节存储容量  

public void ensurecapacity(int minimumcapacity) {  

       if (minimumcapacity > 0)  

           ensurecapacityinternal(minimumcapacity); // 扩展容量大小  

private void ensurecapacityinternal(int minimumcapacity) {  

       // overflow-conscious code  

       if (minimumcapacity - value.length > 0)       // 如果设置的最小容量 > 当前字节存储容量  

void expandcapacity(int minimumcapacity) {  

       int newcapacity = value.length * 2 + 2;      // 自动新增容量,为当前容量的2倍加2(java是unicode编码,占两个字节)  

       if (newcapacity - minimumcapacity < 0)  

           newcapacity = minimumcapacity;  

       if (newcapacity < 0) {  

           if (minimumcapacity < 0) // overflow  

               throw new outofmemoryerror();  

           newcapacity = integer.max_value;  

       value = arrays.copyof(value, newcapacity);  

public abstractstringbuilder append(object obj) {  

public abstractstringbuilder append(string str) {  

       if (str == null) str = "null";  

       int len = str.length();  

       ensurecapacityinternal(count + len);  

       str.getchars(0, len, value, count);  

       count += len;  

       return this;     // 返回对象本身  

public abstractstringbuilder append(stringbuffer sb) {  

public abstractstringbuilder append(charsequence s) {  

       if (s == null)  

           s = "null";  

       if (s instanceof string)  

           return this.append((string)s);  

       if (s instanceof stringbuffer)  

           return this.append((stringbuffer)s);  

       return this.append(s, 0, s.length());        // 返回对象本身  

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

stringbuilde > stringbuffer > string