Blog

Garbage collector and local variables


If you are a C# programmer, then I have a question for you. How do you think, how many times the string "GC called" will be written to console by the following code:

using System;
using System.Threading;

class GarbageCollectorTest
{
   public static void Main()
   {
      Timer t = new Timer(CallGC, null, 1000, 1000);
      Console.ReadKey();
   }

   static void CallGC(object o)
   {
      GC.Collect();
      Console.WriteLine("GC called");
   }
}



Correct answer: depends on compilation parameters. In release build the string will be written only once. Debug version will write it until the user presses a key.


In C++ a local (automatic) variable's lifetime is defined by variable's scope - the variable will be destructed when program flow goes out of the scope.
In C# the lifetime of such variable is defined by how long the variable is used. I.e., the variable may be destructed before it goes out of scope, if garbage collector considers that it's not used any more.
In debug version variable's lifetime is artificially extended to its scope.

In Java, as far as I know, the JVM specification allows similar realization of garbage collector.

P.S.: If you are a C# programmer, but this post became an eye-opener for you, then read Jeffrey Richter's book "СLR via C#". You can find much more interesting and useful for.NET development in it.

Labels: ,


0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home

Optixsoft - Software Development For Fiber Optics. Copyright 2013. All rights Reserved.
optixsoft
Home  |   Company  |   Services  |   Products and solutions  |   Portfolio  |   Client care  |   Contacts  |   Blog  |   Site map