Prayag Gandhi
Prayag Gandhi

Reputation: 9

CLR Garbage Collection For Local variables in .Net

I have a following code segment in one my classes. Please note that this is a static method. What I would like to know is that when I create a new StringBuilder object, what happens to the old one? Does it get garbage collected?

Thanks, Prayag

Public Shared Function CleanUpSql(ByVal s As String) As String
    Dim sb As New StringBuilder(s.Trim())
    RemoveBrackets(sb)
    FixWhiteSpace(sb)
    TrimSemicolon(sb)
    Return sb.ToString()
End Function

Upvotes: 0

Views: 575

Answers (3)

Michael Petrotta
Michael Petrotta

Reputation: 60902

At some point after execution leaves your CleanUpSql method, and thereby leaves the scope in which sb is defined, the StringBuilder referenced by sb will be garbage collected. You don't know exactly when this collection will happen (and you probably don't care).

An object is subject to garbage collection when no in-scope variables reference it.

You can request that collection happen immediately with System.GC.Collect() (which, in, the current implementation of the CLR, performs garbage collection immediately). I'd suggest that you not do this, however - manual garbage collection manipulation is rarely necessary.

If you're interested in more detail, start here.

Upvotes: 4

elevener
elevener

Reputation: 1097

You are creating sb on stack, so as soon as call to CleanUpSql quits sb is not accessible and would be garbage collected. You even don't need to make another call.

Upvotes: 0

Kratz
Kratz

Reputation: 4330

Eventually it does, sometime after the sub exists as the reference to the object exist on the call stack. But its collected whenever the CLR feels the need, not necessarily when you make a new one.

Upvotes: 0

Related Questions