Disposing a StringBuilder object

前端 未结 3 677
时光取名叫无心
时光取名叫无心 2021-02-11 20:36

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

相关标签:
3条回答
  • 2021-02-11 20:44

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

    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.Collect method. 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.

    0 讨论(0)
  • 2021-02-11 21:07

    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.

    0 讨论(0)
  • 2021-02-11 21:10

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

    0 讨论(0)
提交回复
热议问题