Improving JavaScript performance by ditching the Date object
2024-05-02
I had an issue the other day where by the performance of some data processing was being bottlenecked by the performance of using JavaScript date objects.
The scenario is I have a function which over the course of the data processing, is invoked plausibly around 1.2million times, and this has had performance issues a couple of times previously, again related to date operations.
Historically this was solved by creating less dates from strings, by creating date objects and passing them around the application instead of newing dates in the hot path. Reducing processing of date strings. Mutating the date objects where possible instead of copying them, using custom date operation methods instead of 'date-fns'.
However, all this and I still ended up with the issue, that even now with as minimal date processing as possible, the code requires incrementing a date over a series of days (theoretically a lot of days) and the process of incrementing the date multiple times (hundreds, thousands?) per function invocation was still causing a tremendous slow down.
So the first idea was to store the dates as unix timestamps and then perform the needed operations on the timestamp instead and then we are only performing integer operations. The problem was, that this particular function also needed to know which month of the year a date is and how many days are in that month. Which is not so simple to derive from a unix timestamp (that I could figure out) without creating a new Date object.
So the solution I ended up with was to store the dates in a { date, month, year }
structure and implement a set of operations for this structure for adding days, months, parsing ISO strings etc. This is structure only works because we know all of our input data stores dates in strings in the format yyyy-MM-dd.
Rolling this out through our app meant we now did not need to create any Date objects and we were just running our very basic operations (that did the bare minimum to achieve what we needed). This result in a significant boost in performance, processing was taking minutes and this brought it down to around 5 seconds.
So if in JavaScript Dates are giving you performance issues, just consider, you may not actually need them.