gpt4 book ai didi

c# - 当在 stringbuilder 上调用append时,我们是否将字符串添加到堆中?

转载 作者:行者123 更新时间:2023-12-03 22:18:03 27 4
gpt4 key购买 nike

我想知道在 C# 中使用 stringbuilder 的内存使用方面的好处。

如果您有以下场景:

    var strBuilder = new StringBuilder();

for(int i=0;i<1000;i++)
{
strBuilder.Append(i); /// is this not calling i.ToString(); ???
strBuilder.Append(','); /// this i character comma
strBuilder.Append(" and "); /// this is creating a new string " and " right ?
strBuilder.Append(','); // this is a character comma, and not a string, this is value type
}

我的问题如下:每次调用append方法时,我们不是创建一个字符串,然后从stringBuilder中使用它,将其附加并添加到内部字符数组 - 缓冲区中吗?

我假设每当我们附加一些东西时,我们也会创建要附加的字符串,然后它位于堆上,等待被垃圾收集。这不是对堆性能造成影响吗?

最佳答案

are we not creating a string that is then used from the stringBuilder, to be appended and added to the internal character array - buffer ?

在你的正确示例中,是的。必须首先分配该字符串,然后将其添加到内部缓冲区。但是想象一下,您有一个类,其中包含一堆已实例化的属性,并且您希望将它们连接在一起。使用 StringBuilder 附加每个字符串可以在串联过程中节省不必要的分配。

I assume that whenever we append something, we are also creating the string that is to be appended and then this is sitting on the heap, waiting to become garbage collected. Is this not a perfomance hit for the heap ?

该字符串由构建器内部使用:

 unsafe
{
fixed (char* valuePtr = value)
fixed (char* destPtr = &chunkChars[chunkLength])
string.wstrcpy(destPtr, valuePtr, valueLen);
}

然后丢弃并符合收集条件。我不会将堆上的字符串称为性能损失,但它会增加堆的大小,具体取决于您拥有的此类分配数量。

请注意,在循环中,没有理由为每次迭代分配这些字符串。在循环之外声明它们可以节省您的时间。

关于c# - 当在 stringbuilder 上调用append时,我们是否将字符串添加到堆中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30693858/

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