String、StringBuilder、StringBuffer 用法比较

    xiaoxiao2026-01-03  8

    【本文转载于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 ? 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.offset = 0;          this.count = size;          this.value = v;      }      public String(char value[]) {          int size = value.length;          this.offset = 0;          this.count = size;          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.offset = 0;          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(01, data);       // 返回新对象      }  

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

    StringBuffer 构造函数:

    [java]  view plain copy print ? 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);          return this// 返回对象本身      }      public synchronized StringBuffer append(StringBuffer sb) {          super.append(sb);          return this// 返回对象本身      }  

    而在某些特别情况下, 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 ? public StringBuilder() {          super(16);      }      public StringBuilder(int capacity) {          super(capacity);      }      public StringBuilder(String str) {          super(str.length() + 16);          append(str);      }      public StringBuilder(CharSequence seq) {          this(seq.length() + 16);          append(seq);      }      public StringBuilder append(Object obj) {          return append(String.valueOf(obj));      }         public StringBuilder append(String str) {          super.append(str);          return this// 返回对象本身      }      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;          return this// 返回对象本身      }      public StringBuilder append(StringBuffer sb) {          super.append(sb);          return this// 返回对象本身      }  

    在大部分情况下: StringBuilder > StringBuffer

    总结

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

    AbstractStringBuilder 父类构造函数:

    [java]  view plain copy print ? 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)       // 如果设置的最小容量 > 当前字节存储容量              expandCapacity(minimumCapacity);      }      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) {          return append(String.valueOf(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) {          if (sb == null)              return append("null");          int len = sb.length();          ensureCapacityInternal(count + len);          sb.getChars(0, len, value, count);          count += len;          return this;     // 返回对象本身      }      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());        // 返回对象本身      }  

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

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

    StringBuilde > StringBuffer > String

    相关资源:Java 中String StringBuilder 与 StringBuffer详解及用法实例
    最新回复(0)