What's the difference between creating a new instance with "new() and ".StartNew()"?
Asked Answered
T

3

11

Coming from my "answer" to question "Stopwatch in a Task seems to be additive across all tasks, want to measure just task interval"

What are the possible differences between creating a new Stopwatch instance as:

Stopwatch timer = System.Diagnostics.Stopwatch.StartNew();

with

Stopwatch timer = new Stopwatch();
timer.Start();  

Implied subquestion:
Why was StartNew() method provided?

Transact answered 28/4, 2013 at 3:56 Comment(0)
S
15

StartNew, create new instance of the stop watch and starts it as well.

Simple new is Stopwatch instantiation only. It doesn't start the Stopwatch.

For your current code where you are creating a new instance and calling Start, there shouldn't be any difference to Stopwatch.StartNew()

See Stopwatch.StartNew() - MSDN

This method is equivalent to calling the Stopwatch constructor and then calling Start on the new instance.

StartNew provides an easier way to create and start Stopwatch in one step.

Seville answered 28/4, 2013 at 3:58 Comment(0)
R
5

Why was StartNew() method provided?

It's a simpler alternative. StartNew is effectively the same as allocating a new stop watch and starting it instantly.

Since that's a very common use case, the StartNew factory method just simplifies and shortens the API, and reduces the code required to use a stopwatch.

Repel answered 28/4, 2013 at 3:59 Comment(0)
P
1

It initializes a new System.Diagnostics.Stopwatch instance and sets the elapsed time property to zero, and starts measuring elapsed time

and save the one line code to implicitly calling Start() method

Pruter answered 5/2, 2020 at 10:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.