从源码角度简单看StringBuilder和StringBuffer的异同(全面解析)
概述
stringbuilder和stringbuffer是两个容易混淆的概念,本文从源码入手,简单看二者的异同。
容易知道的是,这两者有一个是线程安全的,而且线程安全的那个效率低。
java doc里面的说明
java doc是写源码的人写的注释,先看java doc。
stringbuilder
a mutable sequence of characters. this class provides an api compatible with stringbuffer, but with no guarantee of synchronization. this class is designed for use as a drop-in replacement for 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 stringbuffer as it will be faster under most implementations.
the principal operations on a stringbuilder are the append and insert methods, which are overloaded so as to accept data of any type. each effectively converts a given datum to a string and then appends or inserts the characters of that string to the string builder. the append method always adds these characters at the end of the builder; the insert method adds the characters at a specified point.
for example, if z refers to a string builder object whose current contents are "start", then the method call z.append("le") would cause the string builder to contain "startle", whereas z.insert(4, "le") would alter the string builder to contain "starlet".
in general, if sb refers to an instance of a stringbuilder, then sb.append(x) has the same effect as sb.insert(sb.length(), x).
every string builder has a capacity. as long as the length of the character sequence contained in the string builder does not exceed the capacity, it is not necessary to allocate a new internal buffer. if the internal buffer overflows, it is automatically made larger.
instances of stringbuilder are not safe for use by multiple threads. if such synchronization is required then it is recommended that java.lang.stringbuffer be used.
unless otherwise noted, passing a null argument to a constructor or method in this class will cause a nullpointerexception to be thrown.
since:
1.5
author:
michael mccloskey
see also:
java.lang.stringbuffer
java.lang.string
stringbuffer
a thread-safe, mutable sequence of characters. a string buffer is like a 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.
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.
the principal operations on a stringbuffer are the append and insert methods, which are overloaded so as to accept data of any type. each effectively converts a given datum to a string and then appends or inserts the characters of that string to the string buffer. the append method always adds these characters at the end of the buffer; the insert method adds the characters at a specified point.
for example, if z refers to a string buffer object whose current contents are "start", then the method call z.append("le") would cause the string buffer to contain "startle", whereas z.insert(4, "le") would alter the string buffer to contain "starlet".
in general, if sb refers to an instance of a stringbuffer, then sb.append(x) has the same effect as sb.insert(sb.length(),
whenever an operation occurs involving a source sequence (such as appending or inserting from a source sequence), this class synchronizes only on the string buffer performing the operation, not on the source. note that while stringbuffer is designed to be safe to use concurrently from multiple threads, if the constructor or the append or insert operation is passed a source sequence that is shared across threads, the calling code must ensure that the operation has a consistent and unchanging view of the source sequence for the duration of the operation. this could be satisfied by the caller holding a lock during the operation's call, by using an immutable source sequence, or by not sharing the source sequence across threads.
every string buffer has a capacity. as long as the length of the character sequence contained in the string buffer does not exceed the capacity, it is not necessary to allocate a new internal buffer array. if the internal buffer overflows, it is automatically made larger.
unless otherwise noted, passing a null argument to a constructor or method in this class will cause a nullpointerexception to be thrown.
as of release jdk 5, this class has been supplemented with an equivalent class designed for use by a single thread, stringbuilder. the stringbuilder class should generally be used in preference to this one, as it supports all of the same operations but it is faster, as it performs no synchronization.
since:
jdk1.0
author:
arthur van hoff
see also:
java.lang.stringbuilder
java.lang.string
javadoc小结
从上面可以看出:
stringbuffer和stringbuilder都可以认为是可变的string。
stringbuffer是线程安全的,先出现,在jdk1.0的时候就有了。
stringbuilder是非线程安全的,后出现,在jdk1.5才有。
二者的接口完全一样,stringbuilder更快。
其实,正常的用,知道这几点就好了,不过还是想看看源码里面怎么实现的。
源码
如何实现线程安全
看源码可以知道,这二者都继承了一个抽象类abstractstringbuilder
public final class stringbuffer extends abstractstringbuilder implements java.io.serializable, charsequence public final class stringbuilder extends abstractstringbuilder implements java.io.serializable, charsequence
代码量也不是很大,stringbuilder440行代码,stringbuffer718行代码,最多的是abstractstringbuilder,一共1440行代码。
看代码从几个角度看,一是一些关键的内部结构是怎么样的,二是我们常用的函数是怎么实现的。因为string是不可变的,是放在常量池里面的。猜测stringbuilder和stringbuffer应该是用char数组实现的。
/** * the value is used for character storage. */ char[] value; /** * the count is the number of characters used. */ int count;
可以看出,用value存数据,用一个count表示长度。
看几个常见方法的不同实现。
stringbuffer
@override public synchronized stringbuffer append(string str) { tostringcache = null; super.append(str); return this; } /** * @throws stringindexoutofboundsexception {@inheritdoc} */ @override public synchronized stringbuffer insert(int offset, string str) { tostringcache = null; super.insert(offset, str); return this; } @override public synchronized string tostring() { if (tostringcache == null) { tostringcache = arrays.copyofrange(value, 0, count); } return new string(tostringcache, true); }
stringbuilder
@override public stringbuilder append(string str) { super.append(str); return this; } /** * @throws stringindexoutofboundsexception {@inheritdoc} */ @override public stringbuilder insert(int offset, string str) { super.insert(offset, str); return this; } @override public string tostring() { // create a copy, don't share the array return new string(value, 0, count); }
由代码可知,大部分情况想,strinbbuffer只是增加了一个synchronized关键字来保证线程安全。但tostring方法不同,这个后面再说。
初始化大小和如何增长
既然实际上是一个数组,那么数组开始的大小和增长的方法就很重要,我们通过代码看一下。
/** * constructs a string buffer with no characters in it and an * initial capacity of 16 characters. */ public stringbuffer() { super(16); } /** * constructs a string builder with no characters in it and an * initial capacity of 16 characters. */ public stringbuilder() { super(16); }
可以看到,这两个默认构造函数都说明默认的数组大小是16。
为什么是16呢?我没想明白。
接下来关心如何增长的?我们看看append的实现
public abstractstringbuilder append(string str) { if (str == null) return appendnull(); int len = str.length(); ensurecapacityinternal(count + len); str.getchars(0, len, value, count); count += len; return this; } /** * this method has the same contract as ensurecapacity, but is * never synchronized. */ private void ensurecapacityinternal(int minimumcapacity) { // overflow-conscious code if (minimumcapacity - value.length > 0) expandcapacity(minimumcapacity); } /** * this implements the expansion semantics of ensurecapacity with no * size check or synchronization. */ void expandcapacity(int minimumcapacity) { int newcapacity = value.length * 2 + 2; 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); }
上面三个方法说明了如何扩容。
把当前的容量*2+2
如果新增加的长度大于这个值,则设为新增加的值
如果溢出,则抛出outofmemoryerror
stringbuffer中tostring的实现
/** * a cache of the last value returned by tostring. cleared * whenever the stringbuffer is modified. */ private transient char[] tostringcache; @override public synchronized stringbuffer append(string str) { tostringcache = null; super.append(str); return this; } @override public synchronized string tostring() { if (tostringcache == null) { tostringcache = arrays.copyofrange(value, 0, count); } return new string(tostringcache, true); }
可以看到,定义了一个数组tostringcache,每次数据有变化,都把这个设置为null。在tostring的时候,再重新从当前数据里面拿。
transient关键字是为了避免这个数组被序列化。
小结
其实java本身的源码写的还是比较简单的,学习知识如果能从源码入手,能够更深入的理解很多原理。本文只是简单的列举了一部分源码,简单说明stringbuffer和stringbuilder的异同。有兴趣的朋友可以自己看一下。
以上这篇从源码角度简单看stringbuilder和stringbuffer的异同(全面解析)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。