Is it better to destroy all objects or just let the garbage collector do the job?

I have a function like the following:

Public Function testFunction(ByVal input_string As String) As String

    Dim s As New StringBuilder()
    Dim c As Char
    For i As Integer = 0 To input_string.Length - 1
        c = input_string.Chars(i)
        s.Append(c)
    Next
    Return s.ToString

End Function

but I want know if it's better to explicitly destroy any object, like this:

    Public Function testFunction(ByVal input_string As String) As String

    Dim s As New StringBuilder()
    Dim c As Char
    For i As Integer = 0 To input_string.Length - 1
        c = input_string.Chars(i)
        s.Append(c)
    Next

    Dim t As String = s.ToString
    s = Nothing

    Return t

End Function

or just let the garbage collector do the job for us?

Both the above functions work, but I want only know the best practice for performance...

thank you

Answers


It's always better to let the garbage collector do the job for you. Think about it like this: a programmer much smarter than you (and I) carefully optimized the garbage collection routine to make life much simpler and painless for you. It's unlikely that we can do a better job ourselves, and more likely that we'll just interfere.

Basically, objects that are instantiated as local variables will become eligible for garbage collection as soon as they fall out of scope (i.e., that method finishes execution). Your StringBuilder object is going to be garbage collected whenever the garbage collector runs (which is another thing you don't have to worry about—there is no way to know the next time the GC will run).

Setting an object to Nothing literally does nothing (note that this is different than pre-.NET versions of Visual Basic). It will generally be optimized out by the compiler in Release mode, and even if it isn't, it's not helping you in the least.

However, if an object has a Dispose method, you should be calling it. Or better yet, wrap it in a Using statement. But there's still no reason to set its reference to Nothing.


Setting s = Nothing is pointless as it falls out of scope at the very next instruction thus becoming eligible for garbage collection at that point anyway.

Setting a variable to null/nothing doesn't mean the garbage collection kicks in at that point.


Need Your Help

Swift 1.2 does not have member named 'objectForKey'

swift

After upgrading to Swift 1.2, I got an error:

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.