Waterfrag
Waterfrag

Reputation: 514

Free memory explicitly

I know this may seem like a duplicate, but I think this specific case may be a bit different.

In my MVC application, I have a ViewModel containing a big List used to display a table similar to an Excel sheet. each MyComplexClass contains a list of MyComplexClass and a list of MyComplexColumn.

This makes a pretty big memory usage, but now I have a problem. I am supposed to write a method that cleans my big table, and load a different set of data into it. I could write something like:

    MyViewModel.Lines = new List<MyComplexClass>();
    MyViewModel.LoadNewSetOfData(SetOfData);

But, comming from a C background, explicitly losing my reference on the old List is not something I can do, and continue looking at my face in the mirror every morning.

I saw Here, Here, and Here, that I can set the reference to null, and then call

GC.Collect()

But I was told that I was not really best practice, especially because it may really affects performance, and because I have no way to know if the GC has disposed of this specific memory allocation.

Isn't there any way I can just call something like Free() and live on?

Thank you

Upvotes: 2

Views: 985

Answers (2)

Scott Hannen
Scott Hannen

Reputation: 29302

The short answer - don't worry about garbage collection. The only time I'd be concerned is if you're putting massive amounts of objects and data in a place where they might not get properly garbage collected at all. For example, you store tons of per-user data in ASP.NET session, and it sits there for a long time even though the user visits a few pages and leaves.

But as long as references to objects are released (as when they go out of scope) then garbage collection will do its job. It might not be perfect, but it's really, really good. The work and thought that went into developing good garbage collection in most cases probably exceeds the work that we put into developing the applications themselves.

Although we have the ability to trigger it, the design of the .NET framework deliberately allows us to focus on higher-level abstractions without having to worry about smaller details like when the memory is freed.

Upvotes: 1

Sean
Sean

Reputation: 62532

Don't worry about it! Trying to "encourage" the garbage collector to reclaim memory isn't a great idea - just leave it to do its work in the background.

Just load your different set of data. If memory is getting low the GC will kick in to reclaim the memory without you having to do anything, and if there's plenty of memory available then you'll be able to load the new set without taking the hit of a garbage collection.

Upvotes: 5

Related Questions