清除.NET的StringBuilder的内容最好的方法最好的、方法、内容、NET

2023-09-02 10:55:11 作者:烟嗓

我想问一下你认为是最好的方法(持续时间小于/消耗更少的资源)来清除,以重新使用StringBuilder的内容。想象一下以下情形:

I would like to ask what you think is the best way (lasts less / consumes less resources) to clear the contents in order to reuse a StringBuilder. Imagine the following scenario:

StringBuilder sb = new StringBuilder();
foreach(var whatever in whateverlist)
{
  sb.Append("{0}", whatever);
}

//Perform some stuff with sb

//Clear stringbuilder here

//Populate stringbuilder again to perform more actions
foreach(var whatever2 in whateverlist2)
{
  sb.Append("{0}", whatever2);
}

和清除StringBuilder的时候我能想到的两种可能:

And when clearing StringBuilder I can think of two possibilities:

sb = new StringBuilder();

sb.Length = 0;

什么是清除它,为什么最好的方法是什么?

What is the best way to clear it and why?

感谢你。

编辑:我彪目前的.NET 3.5版本

I ment with current .NET 3.5 version.

推荐答案

如果你正在做这在.NET 2.0或3.5,编写扩展方法来做到这一点是这样的:

If you're doing this in .NET 2.0 or 3.5, write an extension method to do it like this:

/// <summary>
///     Clears the contents of the string builder.
/// </summary>
/// <param name="value">
///     The <see cref="StringBuilder"/> to clear.
/// </param>
public static void Clear(this StringBuilder value)
{
    value.Length = 0;
    value.Capacity = 0;
}

然后,您可以清除它是这样的:

Then, you can clear it like this:

someStringBuilder.Clear();

然后,当4.0出来,你可以赞成的4.0版本沟的扩展方法。

Then, when 4.0 comes out, you can ditch your extension method in favor of the 4.0 version.

更新:这可能不是一个好主意,设置容量为零。这将保证再分配,当你追加到建筑商,如果你重复使用相同的实例。然而,在构建器实例的内存不会被释放,直到你设置容量为一个很小的值(如1)。 Capacity属性的默认值是16,你可能要考虑使用16或(虽然它的效率较低)设置两倍的容量:

UPDATE: It's probably not a good idea to set Capacity to zero. That will guarantee reallocations when you append to the builder, if you're reusing the same instance. However, the memory in the instance of the builder is not released until you set the Capacity to a very small value (such as 1). The default value of the Capacity property is 16. You might want to consider using 16, or (though it's less efficient) setting the capacity twice:

将其设置为1或零清除内存 将其设置为你的原始容量值(这可能不同于16),以恢复它。
 
精彩推荐
图片推荐