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.