开发者

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:

  1. 4 700K
  2. 61 616K
  3. 61 596K
  4. 10 588K
  5. 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜