Out of pure curiosity, is there a way to free the memory used by a StringBuilder
, other than the obvious MyBuilder = New StringBuilder
and MyBuilder.Remove(0, Length)
(although I guess the later wouldn't free anything, would 开发者_JAVA百科it?)
Thanks!
CFP.The best way is to leave it fall out of scope and the GC will take care of the memory.
You are right, using the Remove() method just resets an internal index, it doesn't do anything with the internal array. Not explicitly managing memory is a key property of the .NET framework, the garbage collector sorts it out automatically.
Technically you can by calling GC.Collect(). That is however almost always a Really Bad Idea. Yes, you'll make the StringBuilder instance and its internal array disappear, providing there are no references left to it. But it also promotes other objects in your program too early. Which means they'll stick around longer than necessary, your program will eventually use more memory.
You can either let it fall out of scope or Remove(0, Length) and then set Capacity to 0 (I think it frees the extra memory if you set Capacity to 0, but I am not entirely sure).
You could always use MyBuilder = Nothing
, but I usually just let them fall out of scope.
The way you "free memory" for any object in .NET is to let the GC take care of it.
In the case of a StringBuilder
, just set the instance to Nothing
* and let it be.
I think you might be confused about what it means to "dispose" of objects in .NET. The purpose of the IDisposable
interface is to provide a mechanism by which objects can release access to some shared resource, e.g., file streams. Calling Dispose
is not the same as releasing memory. Since a StringBuilder
does not access any shared resources, it does not need to implement IDisposable
.
If you must force memory to be freed, that's what GC.Collect
is for. But honestly, I've never encountered a scenario where it made sense to call that yourself (as opposed to letting the GC decide when it makes sense to perform a collection).
*I am assuming it's a class-level variable. If it was only a local variable to begin with, there's no need to set it to Nothing
as it will soon fall out of scope anyway.
精彩评论