Why does one loop cause a memory leak?

I came across very strange behavior. 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, private bytes are incremented.

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

How is this possible?

I thought the GC takes care of these things.

In addition, if I compare the behavior of the memory with the version in which I forcefully collect the GC collection every 10 iterations, the result (for me) is surprising:

enter image description here

The green process is one that does not have GC.COllect (), and the black is different.

Could you help me understand the problem?

Thanks!

+4
source share
7 answers

You create a bunch of lines. GK was not going to collect them yet. Ultimately, the memory graph will be plateau. GC works great - no problem here :)

+9
source

GC does not take away memory immediately. That would be very inefficient.

+4
source

Use StringBuilder instead of String and make sure that this does not solve your problem.

+1
source

There is no leak. Remove Thread.Sleep (40); and wait longer, the GC should start after a while.

+1
source

Try changing this:

 String giro = "iteration " + i; Console.WriteLine(giro); 

to

 Console.WriteLine("iteration " + i); 
0
source

If you need a garbage collector, you can name it:

  GC.Collect(); GC.WaitForPendingFinalizers(); 

... its very expensive though ...

0
source

if you define giro from a loop it will solve your problem.

  String giro; while ( true ) { i++; giro = "iteration " + i; Console.WriteLine(giro); Thread.Sleep(40); } 
0
source

Source: https://habr.com/ru/post/1403624/


All Articles