1

I have a method which is going to be called a few 100 times on one call and I have a choice how I want to call the DateTime.UtcNow:

  • Ask for DateTime.UtcNow inside the method and the DateTime.UtcNow is fetched each time; or
  • Give DateTime.UtcNow as a parameter to the method and it is only fetched once (but the DateTime value saved will be a few milliseconds apart for every entry saved, but thats fine).

Now this question has an obvious answer, but now I'm curious: how costly is it to fetch the DateTime.UtcNow?

Omkar
  • 340
  • 3
  • 14

2 Answers2

4

DateTime.UtcNow involves a bit of work and a native call, so it's not completely trivial.

However, you're doing I/O. Regardless of the kind of I/O you're doing, any DateTime.UtcNow calls are going to be completely dwarfed by the I/O. A simple test with debug build and no compiler optimizations on my computer (with my version of the runtime, my version of Windows etc. etc.) shows that I can make seven million DateTime.UtcNow calls per second. It doesn't even use any CPU. There's not much else you can do with the DateTime object that's going to be appreciably faster. Do you save it in the database? That's orders of magnitude slower. Do you save it in a file? Again, orders of magnitude slower. Do you send it back to the client? Again, orders of magnitude slower.

So, unless you need to call DateTime.UtcNow a hundred thousand times during the request, focus on making the code easy to understand. That may mean storing DateTime.UtcNow in a local, or passing it around in a field or through method arguments; or it may mean calling DateTime.UtcNow whenever you want. Maybe you even want to always have the same time during the same request - that's all in your design.

Don't worry about the performance until you actually have a reason to worry.

Luaan
  • 62,244
  • 7
  • 97
  • 116
2

By default, the system clock only updates once every 15ms anyways, so there's no advantage to checking the time over and over in your method. More info on timer resolution here.

As for the efficiency of the method itself - check the reference source. It makes a single call to the CLR to get the file time. The rest of it is high speed ops on an optimized struct. It's unlikely that takes any significant amount of time.

just.another.programmer
  • 8,579
  • 8
  • 51
  • 90