-1

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.

UserControl
  • 14,766
  • 20
  • 100
  • 187
  • Didn't Down Vote, but: It's garbage collected and you are adding a ton of data to a Queue. Just because you set it to `null` doesn't mean it the memory it consumed is immediately freed. By forcing the GC to run, you are getting it removed (though it's a bad idea). The GC will run when it's needed. – vcsjones Mar 23 '11 at 15:49
  • Thanks! Why then on step 5 i'm still have 2 times more memory consumed than on step 1? – UserControl Mar 23 '11 at 15:52
  • hard to say given that the memory total doesn't tell you anything about what's consuming it. It could be additional assembly loads or other bits of the framework being paged in. Are you looking at VM usage or RAM usage? – siride Mar 23 '11 at 15:57
  • RAM usage consumed by the process – UserControl Mar 23 '11 at 16:02
  • When exploring memory "leaks" and other performance issues, try using a performance and memory profiler. See [this question](http://stackoverflow.com/questions/3927/what-are-some-good-net-profilers). – J. Steen Mar 23 '11 at 16:06

1 Answers1

1

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.

Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536