tags:

views:

235

answers:

3

Is there any performance difference in using DateTime.Add(TimeSpan) vs. DateTime.AddDays(double), DateTime.AddHours(double), etc.?

+4  A: 

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.

itowlson
Indeed, there's not much expensive going on there. I took Yuriy's advice re: reflector and see what you're saying here. Just for fun, I ran Add and AddDays through 10 million runs. Add took 1.7 seconds, AddDays took 4 seconds. Definitely fast. Negligible, really. Thanks.
Chris Simmons
A: 

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.

xpda
+2  A: 

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

Michael Petrotta
I like your test code a lot more than mine. Thanks, Michael.
Chris Simmons
No garbage collection between them?
Yuriy Faktorovich