Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explicitly freeing memory in c#

I've create a c# application which uses up 150mb of memory (private bytes), mainly due to a big dictionary:

Dictionary<string, int> Txns = new Dictionary<string, int>(); 

I was wondering how to free this memory up. I've tried this:

Txns = null; GC.Collect(); 

But it doesn't seem to make much of a dent in my private bytes - they drop from say 155mb to 145mb. Any clues?

Thanks

-edit-

Okay I'm having more luck with this code (it gets the private bytes down to 50mb), but why?

Txns.Clear(); // <- makes all the difference Txns = null; GC.Collect(); 

-edit-

Okay for everyone who says 'don't use GC.collect', fair enough (I'm not going to debate that, other than saying you can see my C background coming through), but it doesn't really answer my question: Why does the garbage collector only free the memory if i clear the transaction list first? Shouldn't it free the memory anyway, since the dictionary has been dereferenced?

like image 957
Chris Avatar asked May 05 '09 06:05

Chris


People also ask

How do I free up memory on C?

“free” method in C is used to dynamically de-allocate the memory. The memory allocated using functions malloc() and calloc() is not de-allocated on their own. Hence the free() method is used, whenever the dynamic memory allocation takes place.

Which function is used to free memory in C?

The C library function void free(void *ptr) deallocates the memory previously allocated by a call to calloc, malloc, or realloc.

How does C deallocate memory?

In C, the library function malloc is used to allocate a block of memory on the heap. The program accesses this block of memory via a pointer that malloc returns. When the memory is no longer needed, the pointer is passed to free which deallocates the memory so that it can be used for other purposes.


Video Answer


1 Answers

Private bytes reflect the process' memory usage. When objects are collected the associated memory segment may or may not be freed to the OS. The CLR manages memory at the OS level and since allocating and freeing memory isn't free there's no reason to free each piece of memory immediately as chances are that the application will probably request more memory later.

like image 123
Brian Rasmussen Avatar answered Oct 25 '22 09:10

Brian Rasmussen