Chris Simmons
Chris Simmons

Reputation: 7266

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

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

Upvotes: 2

Views: 1985

Answers (3)

Michael Petrotta
Michael Petrotta

Reputation: 60902

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

Upvotes: 2

xpda
xpda

Reputation: 15813

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.

Upvotes: 0

itowlson
itowlson

Reputation: 74802

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.

Upvotes: 5

Related Questions