Date functions in Mathematica

The date functions in Mathematica are in some regards excellent — you can use almost any common date format and the program will decipher it, and it computes date additions and date differences to high precision, and the date graphing functions work well. However these features come at a cost, the date functions in Mathematica are quite slow.

When writing functions that involve dates, the most important speed optimization is typically to move all date functions outside the inner loops, even if this means doing elaborate computations of all possible date combinations in advance, so that the inner loops can do table lookups for needed results. I have even created my own date functions that, though interpreted rather than compiled as Mathematica’s built in functions are, run ten times faster. (One difference being that my function is less flexible in the format of the inputs it accepts, and can proceed directly with date addition or subtraction, whereas Mathematica’s built-in function must spend epic amounts of time trying to figure out what precisely is meant by, for example “11/5/1980″. However even when you convert all Mathematica dates to AbsoluteTime[] format, it’s still slow.)

I ran some benchmarks tonight, comparing Mathematica to Visual Basic for Applications. This seems a fair comparison, as both are interpreted lanaguages. The inner loop in Mathematica looks like


{DateDifference["11/15/1997", "12/1/1998", "Day"],
DatePlus["11/15/1997", {36, "Day"}],
AbsoluteTime["December 30, 1997"]}

While the equivalent code in VBA is

diff = DateDiff("d", #11/15/97#, #12/1/98#)
sum = DateAdd("d", 36, #11/15/97#)
intTime = DateValue("December 30 1997")

Mathematica 8.01 runs that triad of lines 121 times/second, while VBA completes it about 10,000 times/second. VBA is about 82 times as fast.