Monday, February 21, 2011

Memory Management

So I've been working on several projects involving ASP.NET 4. I've relied heavily on LINQ to talk to my SQL database. I've been curious though about how to deal with my dbml object in a code-behind C# file. For instance usually I just declare a global instance of it in my file, and reference it directly in functions that are called through out the lifetime of the page object. I didn't know if it was better to declare local instances of this object in functions instead. I posted some forum posts about this and I got an unexpected answer. Instead of using either of the above mentioned methods, I should instead use the using statement in C#.
http://msdn.microsoft.com/en-us/library/yh598w02(v=vs.80).aspx

With a 'using' statement, I can create a local instance in my function, and essentially immediately dereference it from memory as soon as my code has left the scope of my 'using'. This provides for much better memory management especially in website's with high user activity, as otherwise your server will continue to load instances of the object through your memory, and you're at the mercy of the garbage collector for when those memory allocations are destroyed.


No comments: