Solve Memory Leak 101

Recently, I was discussing with a few different people about memory leak.

At first, for languages like C#, Java, etc, they all use managed memory and everything (managed resources) is garbage collected if those managed types are no longer reachable. Normally, it is very safe to assume that managed types are always garbage collectable, including arrays, classes, structures. And, of course, if you open a file, database connection, you need include those in a ‘Using’ block, such as the example below.

        // Here 'Using' will dispose command and reader when out of the {} scope. 
        // And the containing class is garbage collected, but it's resources are explicity deallocated. 

	// First access the connection string.
	// ... This may be autogenerated in Visual Studio.
	//
	string connectionString =
	    ConsoleApplication1.Properties.Settings.Default.ConnectionString;
	//
	// In a using statement, acquire the SqlConnection as a resource.
	//
	using (SqlConnection con = new SqlConnection(connectionString))
	{
	    //
	    // Open the SqlConnection.
	    //
	    con.Open();
	    //
	    // The following code uses an SqlCommand based on the SqlConnection.
	    using (SqlCommand command = new SqlCommand("SELECT TOP 2 * FROM Dogs1", con))
	    using (SqlDataReader reader = command.ExecuteReader())
	    {
		while (reader.Read())
		{
		    Console.WriteLine("{0} {1} {2}",
			reader.GetInt32(0), reader.GetString(1), reader.GetString(2));
		}
	    }
	}

For .Net, you can use .Net Memory Profiler, and video tutorial

NET Memory Profiler is a powerful tool for finding memory leaks and optimizing the memory usage in programs written in C#, VB.NET or any other .NET Language.

.NET Memory Profiler will help you to:

View real-time memory and resource information
Easily identify memory leaks by collecting and comparing snapshots of .NET memory
Find instances that are not properly disposed
Get detailed information about unmanaged resource usage
Optimize memory usage
Investigate memory problems in production code
Perform automated memory testing
Retrieve information about native memory

And you must read this great article from Raymond Chen about garbage collection about how everybody thinks about garbage collection in the wrong way.

Tagged on: , ,

Leave a Reply