Queue<T> memory usage and weird GC behavior
Here is a small console program i'm playing with to find out why my production app consumes too much memory:
using System;
using System.Collections.Generic;
namespace ConsoleApplication1 {
class Program {
static void Main(string[] args) {
Console.WriteLine("Press key - 1"); Console.ReadLine();
var q = new Queue<string>();
for (int i = 0; i < 1000000; i++)
q.Enqueue("test string" + i);
Console.WriteLine("Press key - 2"); Console.ReadLine();
q = null;
Console.WriteLine("Press key - 3"); Console.ReadLine();
GC.Collect();
开发者_如何转开发 Console.WriteLine("Press key - 4"); Console.ReadLine();
GC.Collect(2);
Console.WriteLine("Press key - 5"); Console.ReadLine();
}}}
I'm running it and monitoring Windows task manager while pressing the key. Here is what i see in Memory column on each step:
- 4 700K
- 61 616K
- 61 596K
- 10 588K
- 8 588K
The results vary slightly (just few Ks) from run to run but you get the picture. Can please someone explain what's going on here?
My environment: .NET4 (client profile), Windows 7 x64.
You found out why the jitter generates no code when you set a local variable to null. The garbage collector already knows when you stop referencing an object, it doesn't need help like that. There are many books about .NET that can explain this to you, Richter's "CLR via C#" is widely praised.
精彩评论