Optixsoft Blog

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: ,


C# quick question.


Can you quickly specify three advantages of automatic property over public field, as a member of a class?
I.e., why is the following code:
public string Foo{ get; set; }
better than this:
public string Foo;

The asnwer is (as often) on StackOverflow.

Labels:


NOPs and debug


It's often necessary to edit source code during debug. To make this fixes to take effect, usually, you need to rebuild your application and restart the debug session. But there is edit-and-continue feature in Microsoft Visual Studio, which allows these fixes to take effect without restarting of the application. Ever thought about how it works?

The secret is in NOP instructions, which compiler inserts in certain places of executable code. These instructions can be replaced with new code later. Also, they allow to place breakpoints at those source code lines, which have no correspondent executable code. E.g., at the beginning of code block (opening brace in C++ and C#). Or at the operator, that would otherwise be replaced during optimization.

BTW: NOP-instructions may also be reasonable in application's release-version. E.g., to align code block for better caching.

Labels: , ,


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