25 June 2016

use DateTime.UtcNow instead of DateTime.Now.ToUniversalTime()

Often times juniors developers in the team use DateTime.Now.ToUniversalTime() to get the UTC time instead of using the direct approach DateTime.UtcNow.

Let’s go though the below points to understand the difference between the two.

  • It looks like .NET maintains the DateTime value internally in UTC time zone.
  • When you call DateTime.Now. ToUniversalTime (), actually the .NET code does two things.
    1. First, with “DateTime.Now”, converts the UTCTime to machine’s local time zone.
    2. Then on calling on the ToUniversalTime (), it converts the local time to UTC time zone again.

Obviously there is a overhead associated with using DateTime.Now.ToUniversalTime() instead of DateTime.UtcNow when you just want UTC time.

This slight run-time overhead might doesn't matter always; but while processing huge volume of operation involving code using DateTime.Now.ToUniversalTime (), can incur more CPU cost.

Apart of the cost associated, the construct “DateTime.UtcNow” looks more readable than DateTime.Now.GetUniveralTime().

So if you are using ToUniversalTime() method to get the UTC time, consider to use DateTime.UtcNow. Do this change as early, otherwise you might run the risk of this “not so good” practice getting repeated in your code base by developers adding the new code into the project.

Benchmarking

Executed the code using “DateTime.UtcNow” and “DateTime.Now. ToUniversalTime()” to get the UTC time million times in a loop like below:

Stopwatch watcher = new Stopwatch();
watcher.Start();
for (int i = 0; i < 1000000; i++)
{
  DateTime dateTime = DateTime.UtcNow;
   // DateTime dateTime = DateTime.Now.ToUniversalTime();
}
 
watcher.Stop();
Console.WriteLine(watcher.ElapsedMilliseconds.ToString());

Benchmarking results:

  • The code using “DateTime.UtcNow” took 13 millisecond to complete the for-loop execution.
  • The code using “DateTime.Now.ToUniversalTime()” took 400 millisecond to complete the for-loop execution.

No comments:

Post a Comment