User987 User987 - 4 years ago 142
C# Question

Minimizing usage of RAM by created objects in runtime in C#

I was wondering what are the best practices when creating objects, performing LINQ in C#. For instance, I realize that when I open up a connection using LINQ I should be putting the model object into a using statement like this:

using(var ctx = new mymodel())
{

}


Now, what about the objects that are EF classes?

They do not implement IDisposable interface thus I can't do something like this when creating an object like this for example:

using(var user = new Users())
{

}


But when an action is called like this:

public ActionResult InsertUser()
{

var user = new Users();

}


I have no clear picture what happens with this object once the insert into the db is finished. Does this object stays allocated in memory or it gets released? If not, what are best practices to release memory once they aren't needed anymore..?

On the other there are static variables as well...

So to sum things up, my questions are:


  • what are best practices to release memory when creating instances of an object of a class?

  • Is implementation of IDisposable interface on every class that I have good choice?

  • When a static variable is created in .NET MVC, what is the best way to release memory taken by this kind of variables?

  • Same question goes for Session object?



P.S. Guys, I'd really appreciate if all of you that are reading this to post your opinion or post some useful links for some documentations/blog posts so that I can expand my horizons =)

Answer Source

Before you do any performance tweaks I highly recommend to run a memory profiler (for example JetBrains dotMemory, but there are others) and find out the actual source of the problem. Without information from profiler, your optimisations will be like sticking your finger at a sky and shouting "Rainbow!" i.e. useless at best, harmful at worst.

Also after identifying issues with profiler, but before starting changing your code, I recommend reading about how Garbage Collection works in .Net. Here are some references to get you started:

  1. MSDN Garbage Collection
  2. MSDN Garbage Collector Basics and Performance Hints
  3. .Net Garbage Collection in depth

Here are some links to answer your questions:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download