11

Consider the following method:

DoTimeIntensiveOperation()
{
    var t = new Stopwatch();

    foreach(var element in a_very_long_array)
    {
        DoATimeConsumingTask(element);
    }

    Console.WriteLine("Took me " + t.Elapsed);
    return;
}

Do I need to call t.Stop() before returning?

As far as I know, the garbage collector will destroy anything that doesn't have a reference chain going back to the main method. The only reference to the created Stopwatch is t, so when DoTimeIntensiveOperation, t will be freed and the Stopwatch should be eligible for destruction. But does the fact that it's still "ticking" interfere with the GC?

Superbest
  • 25,318
  • 14
  • 62
  • 134
  • Also here: [Should I Stop Stopwatch at the end of the method?](https://stackoverflow.com/questions/24140261/should-i-stop-stopwatch-at-the-end-of-the-method) – nawfal Nov 16 '22 at 19:40

1 Answers1

12

No, I threw this quick test and it seems that once the GC is run, the stopwatch is destroyed. (Feel free to correct the code)

 static void Main(string[] args)
 {
      DoTimeIntensiveOperation();

      GC.Collect();
      while (swRef.IsAlive)
      {
      }
      Console.WriteLine("Destroyed");
 }

 static WeakReference swRef = null;
 static void DoTimeIntensiveOperation()
 {
     Stopwatch sw = new Stopwatch();
     sw.Start();
     swRef = new WeakReference(sw);
     return;
 }

The output is Destroyed when GC.Collect is called. Of course, in a real program you're unlikely to explicitly call GC.Collect but this is to show that the Stopwatch object is destroyed once out the scope of the method even if Stop hasn't been called.

keyboardP
  • 68,824
  • 13
  • 156
  • 205