I create a simple test program to find out the memory and speed difference between calling Dispose vs not calling it for DataContainer object.
Here my test program:
static void Main(string[] args)
{
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
for (int i = 0; i < 5000; i++)
{
// I change the following call with Method1 and run it again
var res = Method2();
int count = res.Count;
}
stopwatch.Stop();
Console.WriteLine(stopwatch.Elapsed);
Console.WriteLine("Mem: " + System.Diagnostics.Process.GetCurrentProcess().PrivateMemorySize64.ToString("N"));
Console.ReadKey();
}
private static IList Method1()
{
using (var db = new Model.SampleEntities())
{
var result = db.People.Where(p => p.Name.StartsWith("a")).Take(1);
return result.ToList();
}
}
private static IList Method2()
{
var db = new Model.SampleEntities();
var result = db.People.Where(p => p.Name.StartsWith("a")).Take(1);
return result.ToList();
}
The results are the same for both methods. The result on my PC was about 27.22 seconds and about 37.7 MB of private memory size.
Now why should I call Dispose for DataContainers while it doesn't differ?
Thanks in advance.
Id imagine Model.SampleEntities returns an IDisposable for a good reason - perhas properly cleaning up managed and/or unmanaged resources etc