Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I need to stop the stopwatch if the enclosing method is about to return?

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?

like image 748
Superbest Avatar asked Apr 21 '13 17:04

Superbest


People also ask

Do I need to call stopwatch stop?

No, there is no need to stop or clean it up. Stopwatch does not use any unmanaged resources (if you thought of IDisposable ). It actually does not use any resources at all (except the memory used by the object itself, of course)! It also does not consume any CPU while measuring the elapsed time!

How do you stop a stopwatch in Java?

You can either cancel the entire Timer by calling Timer. cancel() , or you can cancel individual tasks by calling TimerTask. cancel() .


1 Answers

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.

like image 130
keyboardP Avatar answered Oct 10 '22 09:10

keyboardP