前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >源码超度:String、StringBuffer、StringBuilder

源码超度:String、StringBuffer、StringBuilder

作者头像
用户2146693
发布2021-12-28 10:42:19
2260
发布2021-12-28 10:42:19
举报

概要

String、StringBuffer、StringBuilder是常用的字符序列,从源码上对比下,三者的区别

类结构

String

StringBuffer

StringBuilder

  1. 都实现了interface CharSequence,interface Comparable<T>,interface Serializable
  2. StringBuilder,StringBuffer继承了abstract class AbstractStringBuilder

CharSequence: A CharSequence is a readable sequence of char values. This interface provides uniform, read-only access to many different kinds of char sequences.

Comparable: This interface imposes a total ordering on the objects of each class that implements it.This ordering is referred to as the class's NATURAL ORDERING, and the class's compareTo method is referred to as its natural comparison method

Serializable: Serializability of a class is enabled by the class implementing the java.io.Serializable interface.

AbstractStringBuilder: A MUTABLE SEQUENCE of characters. Implements a modifiable string. At any point in time it contains some particular sequence of characters, but the length and content of the sequence CAN BE CHANGED through certain method calls.

Appendable:An object to which char sequences and values can be appended.


数据结构

String

final 型byte数组,不可修改性的源头。

StringBuffer、StringBuilder

java.lang.AbstractStringBuilder中:

    /**
     * The value is used for character storage.
     */
    byte[] value;

通过继承java.lang.Appendable支持修改

设计目标

String

Strings are constant; their values cannot be changed after they are created. 
String buffers support mutable strings.Because String objects are immutable they can be shared

StringBuffer

 * A thread-safe, mutable sequence of characters.
 * A string buffer is like a {@link String}, but can be modified. At any
 * point in time it contains some particular sequence of characters, but
 * the length and content of the sequence can be changed through certain
 * method calls.
 * <p>
 * String buffers are safe for use by multiple threads. The methods
 * are synchronized where necessary so that all the operations on any
 * particular instance behave as if they occur in some serial order
 * that is consistent with the order of the method calls made by each of
 * the individual threads involved.

StringBuilder

 * A mutable sequence of characters.  This class provides an API compatible
 * with {@code StringBuffer}, but with no guarantee of synchronization.
 * This class is designed for use as a drop-in replacement for
 * {@code StringBuffer} in places where the string buffer was being
 * used by a single thread (as is generally the case).   Where possible,
 * it is recommended that this class be used in preference to
 * {@code StringBuffer} as it will be faster under most implementations.

无参构造函数

String

    /**
     * Initializes a newly created {@code String} object so that it represents
     * an empty character sequence.  Note that use of this constructor is
     * unnecessary since Strings are immutable.
     */
    public String() {
        this.value = "".value;
        this.coder = "".coder;
    }

StringBuffer、StringBuilder

java.lang.AbstractStringBuilder中:

    /**
     * Creates an AbstractStringBuilder of the specified capacity.
     */
    AbstractStringBuilder(int capacity) {
        if (COMPACT_STRINGS) {
            value = new byte[capacity];
            coder = LATIN1;
        } else {
            value = StringUTF16.newBytesFor(capacity);
            coder = UTF16;
        }
    }
    /**
     * Constructs a string buffer with no characters in it and an
     * initial capacity of 16 characters.
     */
    @HotSpotIntrinsicCandidate
    public StringBuffer() {
        super(16);
    }
    /**
     * Constructs a string builder with no characters in it and an
     * initial capacity of 16 characters.
     */
    @HotSpotIntrinsicCandidate
    public StringBuilder() {
        super(16);
    }

默认byte[]初始化长度时16,调用append方法时,长度不够,会扩容,进行数组复制。

已知内容的情况下,可以通过指定长度,来避免扩容、减少数组复制。

一般情况下,可以不用考虑这么多,性能要求严格的情况下,需要考虑减少数组复制。

Arrays.copyOf底层是java.lang.System#arraycopy,arraycopy在JVM层面,会有更高效的方法替代。

总结

  1. String 初始化后不可修改,StringBuilder、StringBuffer支持修改。
  2. 操作少量的数据或者常量使用 String
  3. 单线程操作字符串缓冲区下操作大量数据,使用StringBuilder
  4. 多线程操作字符串缓冲区下操作大量数据,使用StringBuffer
  5. 性能严格要求的场景下,StringBuilder、StringBuffer可以通过指定初始化容量,减少数组复制
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 概要
  • 类结构
    • String
      • StringBuffer
        • StringBuilder
        • 数据结构
          • String
            • StringBuffer、StringBuilder
            • 设计目标
              • String
                • StringBuffer
                  • StringBuilder
                  • 无参构造函数
                    • String
                      • StringBuffer、StringBuilder
                      • 总结
                      领券
                      问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档