Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disposing a StringBuilder object

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.

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.

like image 972
Druid Avatar asked Aug 25 '09 21:08

Druid


People also ask

How do you dispose of StringBuilder?

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.

Does StringBuilder implement IDisposable?

No, StringBuilder doesn't implement IDisposable , so it can't be used with using .

In which generation does the StringBuilder objects get collected?

All the objects are created in G0 and released from G0 itself. So, here we see that there is a significant difference in both memory usage as well as GC's bucket movements. Hence, we can conclude that we should prefer to use StringBuilder, rather than String, especially when we are dealing with concatenations.


2 Answers

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.

like image 176
mmx Avatar answered Sep 22 '22 01:09

mmx


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

like image 43
Jason Williams Avatar answered Sep 26 '22 01:09

Jason Williams