C# 处理 StringBuilder 对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1331002/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 15:14:30  来源:igfitidea点击:

Disposing a StringBuilder object

c#winformsmemory-managementmemory-leaksstring

提问by Druid

How does one effectively dispose a StringBuilderobject? If an user generates multiple reports in a single sitting, my app ends up using a huge amount of memory.

一个人如何有效地处置一个StringBuilder对象?如果用户一次生成多个报告,我的应用程序最终会使用大量内存。

I've read in a few sites online that the follow may help:

我在一些在线网站上阅读了以下内容可能会有所帮助:

StringBuilder sb = new StringBuilder(1000000);

// loop goes here adding lots of stuff to sb

exampleObject.Text = sb.ToString();

sb.Length = 0;

Does the last line really help? Any other way of dealing with this?

最后一行真的有帮助吗?有没有其他办法处理这个问题?

NB: This does not really stop my users from continuing to use the application. I'm just wondering if there is a way of avoiding redundant memory usage.

注意:这并没有真正阻止我的用户继续使用该应用程序。我只是想知道是否有办法避免冗余内存使用。

采纳答案by Mehrdad Afshari

No, a StringBuilderis a purely managed resource. You should just get rid of all references to it. Everything else is taken care of by the garbage collector:

不,aStringBuilder是纯托管资源。您应该摆脱对它的所有引用。其他一切都由垃圾收集器处理:

StringBuilder sb = ...;
// ... do work
sb = null; // or simply let it go out of scope.

In .NET, there's no deterministic delete(like C++, where you free up memory allocated to a single object.) Only GC can free memory. By forfeiting all references to an object, you'll let GC be able to deallocate the object if it wants to. You can force a garbage collection by calling the System.GC.Collectmethod. However, it's not recommended to manipulate with GC unless you really know what you are doing. GC is smart. It's rarely beneficial to force it.

在 .NET 中,没有确定性delete(如 C++,您可以释放分配给单个对象的内存。)只有 GC 可以释放内存。通过放弃对一个对象的所有引用,您将让 GC 能够根据需要释放该对象。您可以通过调用该System.GC.Collect方法来强制进行垃圾回收。但是,除非您真的知道自己在做什么,否则不建议使用 GC 进行操作。GC 很聪明。强迫它很少有好处。

回答by Lasse V. Karlsen

Unless the 'excessive memory usage' is a problem, I would leave it as it is and not worry about it.

除非“过多的内存使用”是一个问题,否则我会保持原样而不用担心。

.NET is in most cases smart enough to avoid doing a garbage collection if you have enough memory available.

如果您有足够的可用内存,.NET 在大多数情况下足够聪明,可以避免进行垃圾回收。

回答by Jason Williams

If you are generating many reports, you could consider re-using a single StringBuilder instead of allocating a new one for each report.

如果要生成许多报告,则可以考虑重新使用单个 StringBuilder,而不是为每个报告分配一个新报告。