StringBuilder的內(nèi)部數(shù)據(jù)結(jié)構(gòu)如下:
添加字符串:
StringBuilder Append(String value)
當 value 的大小可以放入當前 sb淘菩,則直接字符串拷貝。
unsafe {
fixed (char* valuePtr = value)
fixed (char* destPtr = &chunkChars[chunkLength])
string.wstrcpy(destPtr, valuePtr, valueLen);
}
否則寻行,需要擴容。
擴容代碼:
int newBlockLength = Math.Max(minBlockCharCount, Math.Min(Length, MaxChunkSize));
// Copy the current block to the new block, and initialize this to point at the new buffer.
m_ChunkPrevious = new StringBuilder(this);
m_ChunkOffset += m_ChunkLength;
m_ChunkLength = 0;
// Check for integer overflow (logical buffer size > int.MaxInt)
if (m_ChunkOffset + newBlockLength < newBlockLength)
{
m_ChunkChars = null;
throw new OutOfMemoryException();
}
m_ChunkChars = new char[newBlockLength];
先將當前 chunk 填滿醋奠,然后將當前 chunk 的內(nèi)容填入一個新建的 sb莫换,并作為前置,然后重置當前sb响蕴,再拷貝剩余字符串內(nèi)容谆焊。
每發(fā)生一次擴容時,都會多一次前置操作浦夷,從而形成了單鏈表辖试,并且由m_ChunkOffset標識出每個sb的首字符在總字符串的位置。
輸出
public override String ToString()
了解了如何添加军拟,再理解如何輸出就不難了剃执。
string ret = string.FastAllocateString(Length);
StringBuilder chunk = this;
unsafe {
fixed (char* destinationPtr = ret)
{
do
{
if (chunk.m_ChunkLength > 0)
{
// Copy these into local variables so that they are stable even in the presence of ----s (hackers might do this)
char[] sourceArray = chunk.m_ChunkChars;
int chunkOffset = chunk.m_ChunkOffset;
int chunkLength = chunk.m_ChunkLength;
// Check that we will not overrun our boundaries.
if ((uint)(chunkLength + chunkOffset) <= ret.Length && (uint)chunkLength <= (uint)sourceArray.Length)
{
fixed (char* sourcePtr = sourceArray)
string.wstrcpy(destinationPtr + chunkOffset, sourcePtr, chunkLength);
}
else
{
throw new ArgumentOutOfRangeException("chunkLength", Environment.GetResourceString("ArgumentOutOfRange_Index"));
}
}
chunk = chunk.m_ChunkPrevious;
} while (chunk != null);
}
}
從后向前,按照offset指示的起始位置懈息,將內(nèi)容拷貝至總的字符串肾档。
可以看出,由于是一次性分配了所需要的所有內(nèi)存辫继,所以在【很多次循環(huán)】場景下怒见,比String.Concat效率要高出很多。