Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does a single loop cause a memory leak?

I'm facing with a very strange behaviour. With this dummy code:

 static void Main( string[] args )
    {
        int i = 0;

        while ( true )
        {
            i++;

            String giro = "iteration " + i;

            Console.WriteLine(giro);

            Thread.Sleep(40);
        }
    }

Using perfom the private bytes are increasing.

img http://dl.dropbox.com/u/2478017/memory.gif

How is it possible?

I thought GC takes care of these stuffs.

Moreover, if I compare memory behavior of this with a version in which i force GC collection every 10 iterations, the result is (for me) surprising:

enter image description here

The green process is the one with no GC.COllect(), and black one is the other.

Could you help me to understand the issue?

Thanks!

like image 225
ff8mania Avatar asked Dec 06 '22 15:12

ff8mania


2 Answers

You're creating a bunch of strings. The GC hasn't seen fit to collect them yet. Eventually the memory graph will plateau. The GC works fine - there's no problems here :)

like image 98
Jon Skeet Avatar answered Dec 09 '22 03:12

Jon Skeet


The GC doesn't tidy up memory straightaway. That would be very inefficient.

like image 44
Skizz Avatar answered Dec 09 '22 05:12

Skizz