Use DateTime.UtcNow instead of DateTime.Now for better performance (CSharp/C# code)



Always tries to use DateTime.UtcNow instead of DateTime.Now especially when you are using it inside for, foreach or while loop. Because DateTime.Now is slower and if using inside a loop it will show down your pc. The DateTime.UtcNow will give you the universal time which is much faster.

Please see the implementation details of DateTime.Now: (using decompiler)

public static DateTime Now
{
    get
    {
        DateTime utcNow = UtcNow;
        bool isAmbiguousLocalDst = false;
        long ticks = TimeZoneInfo.GetDateTimeNowUtcOffsetFromUtc(utcNow, out isAmbiguousLocalDst).Ticks;
        long num2 = utcNow.Ticks + ticks;
        if (num2 > 0x2bca2875f4373fffL)
         {
             return new DateTime(0x2bca2875f4373fffL, DateTimeKind.Local);
         }
        if (num2 < 0L)
        {
             return new DateTime(0L, DateTimeKind.Local);
         }
        return new DateTime(num2, DateTimeKind.Local, isAmbiguousLocalDst);
    }
}

You can see above that there is a lot of stuff going on there just to return local time.  By contrast, lets have a look at DateTime.UtcNow:

// This is approximatly 120 times faster than DateTime.Now above
public static DateTime UtcNow
{
    [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries"), SecuritySafeCritical]
    get
     {
        return new DateTime((ulong) ((GetSystemTimeAsFileTime() + 0x701ce1722770000L) | 0x4000000000000000L));
    }
}


Post Article  Post Code 
  Post Tip    Start Forum
 
Quick note for developers
Google+
Follow