c# compiler mem"leakage"

  • Thread starter Thread starter Doker
  • Start date Start date
D

Doker

Lets consider following code:

while (true)
{
string[] t = new String[1024 * 1024 * 20];
}

You probably thing this is the good solution because "narrow scope of
variable to the minimum". But wait. Mem usage is at level of 300MiB!

Now. Lets see what happens if we use:

string[] t;
while (true)
{
t = null;
t = new String[1024 * 1024 * 20];
}
Wow! Now mem is something at 30MiB. Who could know that?
So this is either compiler bug or framework's thing.

By the way: Add GC.Collect() for your VS not to hang up for a moment
when you stop or pause. Do it like that:
string[] t;
while (true)
{
t = null;
GC.Collect();
t = new String[1024 * 1024 * 20];
}
 
Doker said:
Lets consider following code:

while (true)
{
string[] t = new String[1024 * 1024 * 20];
}

You probably thing this is the good solution because "narrow scope of
variable to the minimum". But wait. Mem usage is at level of 300MiB!

Hmm. I don't see that at all. Are you seeing it when you run in the
debugger, or in release mode? How are you measuring the memory usage?
 
Jon Skeet [C# MVP] pisze:
Doker said:
Lets consider following code:

while (true)
{
string[] t = new String[1024 * 1024 * 20];
}

You probably thing this is the good solution because "narrow scope of
variable to the minimum". But wait. Mem usage is at level of 300MiB!

Hmm. I don't see that at all. Are you seeing it when you run in the
debugger, or in release mode? How are you measuring the memory usage?
Try in debug mode. I see it in Task manager by the app name entry.
Vista x64, VS SP1.
 
Try in debug mode. I see it in Task manager by the app name entry.
Vista x64, VS SP1.

When you run something in debug mode, that changes the garbage
collection behaviour in subtle ways. If it's not a problem when
running outside the debugger, I'm not sure that I really view it as an
issue.

Jon
 
Back
Top