gpt4 book ai didi

c# - StringBuilder 是否在调用 ToString() 时缓存结果字符串?

转载 作者:行者123 更新时间:2023-11-30 19:53:50 27 4
gpt4 key购买 nike

StringBuilder 是否在调用 ToString 时缓存字符串?例如,这会创建两个不同的内存中字符串,还是只使用一个:

var sb = new StringBuilder();
sb.Append("foo");
sb.Append("bar");

var str1 = sb.ToString();
var str2 = sb.ToString();

它会为连续读取操作缓存自己的结果吗?

最佳答案

查看 source code对于 StringBuilderToString()。答案是否定的

    [System.Security.SecuritySafeCritical]  // auto-generated
public override String ToString() {
Contract.Ensures(Contract.Result<String>() != null);

VerifyClassInvariant();

if (Length == 0)
return String.Empty;

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);
}
}
return ret;

关于c# - StringBuilder 是否在调用 ToString() 时缓存结果字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46196398/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com