If I’m any indication, any of us who studied programming with C/C++ still have nightmares about manual memory management. Actually, I have nightmares in Assembly (shudder). I’m not sure they still teach that stuff these days… If you don’t know, the concept is simple: When your code creates an object, the runtime system allocates space in memory to store it. Eventually, that space needs to be released and reused, or else memory usage will keep increasing and the computer will crash due to an out-of-memory state. So, space in memory has to be managed, either by manually including code to release old objects or by some more automated process.

These days, modern-day runtimes (like the .NET Framework’s CLR) include automated garbage collection. In my opinion, the biggest effect of this is developer laziness. We can sit back and blame high memory usage and persistent leaks on the framework… No, it couldn’t be our own shoddy code causing it! The automated garbage collector is slow to clean up (since it doesn’t want to accidentally delete some objects from memory that are actually in use!), and sometimes it misses things. This is why applications end up hogging more and more memory over time. With the assumption that automatic means perfect, we just tend to ignore it and assume it’s a non-issue or something no one can help.

For those who care about memory usage, though, the “using” keyword in .NET is a great way to help optimize garbage collection. Basically, “using” ensures the base Dispose() method is called for your object when you’re done with it. Naturally, your object has to implement the IDisposible interface for this to apply. Running the Dispose() method does not actually mean it is immediately deleted from memory, as some might assume. However, it does effectively “flag” the objected for garbage collection so it gets deleted in a more optimized manner–that is, quickly and consistently. It’s also easy to use and can save you a few lines of code, too.

To ensure optimized garbage collection, you might write some code like this:

[C#]
try
{
SqlConnection db = new SqlConnection();

// connect and do stuff
// ...
}
finally
{
if (db != null)
db.Dispose();
}

With the “using” keyword, you can cut this down significantly in a nice, condensed little structure:

[C#]
using (SqlConnection db = new SqlConnection())
{
// connect and do stuff
// ...
}

For you VB.NET programmers… The long way:

[VB.NET]
Dim db As New SqlConnection()
Try
' connect and do stuff
' ...
Finally
If db IsNot Nothing Then
db.Dispose()
End If
End Try

And the short way:

[VB.NET]
Using db As New SqlConnection()
' connect and do stuff
' ...
End Using

For you F# programmers…

[F#]
// Come on, if you're using F# you like unnecessary challenges. No example, figure it out yourselves!

Like this post? Share it!
Free WordPress Themes, Free Android Games