开发者

DateTime.Add(TimeSpan) performance vs DateTime.AddDays/Hours/etc* methods

Is there any performance difference in using DateTime.Add(TimeS开发者_运维知识库pan) vs. DateTime.AddDays(double), DateTime.AddHours(double), etc.?


Add(TimeSpan) calls AddTicks directly with the ._ticks member of the TimeSpan. AddDays, etc., do a multiplication and range check, then call AddTicks. So Add(TimeSpan) is probably fractionally faster, but almost certainly insignificantly so: all will be blindingly fast.


This simple benchmark indicates that using a TimeSpan might be a bit faster, but both are extremely fast, doing 10 million iterations in under a second. Execution time will be swamped by other aspects of your code.

[MethodImpl(MethodImplOptions.NoOptimization)] 
static void Main(string[] args)
{
    Stopwatch sw= new Stopwatch();
    DateTime d = DateTime.Now;
    sw.Start();
    for (int i = 0; i < 10000000; i++)
    {
        DateTime d2 = d.AddHours(10);
    }
    sw.Stop();
    Console.WriteLine(sw.Elapsed);

    sw.Reset();
    sw.Start();
    for (int i = 0; i < 10000000; i++)
    {
        DateTime d2 = d + new TimeSpan(10, 0, 0);
    }
    sw.Stop();
    Console.WriteLine(sw.Elapsed);
}

// Core2 Duo, Win7. Ratio holds up under repeated tests
00:00:00.4880733 // AddHours
00:00:00.4404034 // add TimeSpan


dattimeadd(timespan) is, in fact, a little faster than datetime.adddays and addhours, but not enough to matter in almost any practical case. At 500,000 iterations, it's inconclusive. At 2,000,000 iterations, you can see a difference.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜