0

Is using C# Stopwatch affects performance on multithreading applications. Could not find any reason why it should affect performance and because I heard it in the past I want to hear more thoughts.

gcohen12
  • 9
  • 1
  • Have a look at the sources of Stopwatch implementation and you will know for sure how it will affect performance – Sir Rufo Apr 27 '22 at 07:08
  • 1
    Rather than trying to maintain a list, billions of entries long, of things that can or cannot affect performance, please choose the other option - set performance *goals*, write straightforward code, *measure*, and **if and only if** you have a performance problem, use a profiler to locate the *actual source of the problem*. – Damien_The_Unbeliever Apr 27 '22 at 07:15
  • Could you include in the question an example of how you intend to use the `Stopwatch` class in a multithreaded application? This could make your question answerable. Currently it's too broad IMHO. – Theodor Zoulias Apr 27 '22 at 07:28

1 Answers1

1

Yes

Using Stopwatch will definitely have an impact on performance:

  1. Calling new Stopwatch() or Stopwatch.StartNew() will allocate a small amount of memory on the heap.
  2. The timer that is used ties directly into the operating system. There will certainly be a small amount of overhead involved when the .NET platform does the native calls into the timer APIs, which will vary depending on operating system.

However, whether the amount of overhead is acceptable for an application depends on the application requirements. Some general advice:

  1. Where possible, reuse instances of Stopwatch instead of instantiating them.
  2. Benchmark your application (using BenchmarkDotNet) with and without Stopwatch to see what the actual difference is.
  3. If the timing code is an optional part of the application, consider putting in a way to either conditionally compile it out of the app or disable it as a feature.
NightOwl888
  • 55,572
  • 24
  • 139
  • 212