I'm in need of help to profile where the slow part(s) of this relative-date util logic is, and find reasonable tweaks or work-arounds to thse bottlenecks.
I'm actually happy to even pay a bit of a bounty ($USD) for someone who can produce an analysis of the actual problem(s) and clear, workable solutions.
Here's an example estimated threshold for improvement that might be helpful (and earn a bounty): the 500-iteration loop above might be taking 200-300ms (on my system), and I need it to be able to run in less than 10ms (which should be completely doable I think, it's not that complex of logic).
IOW, we're going to need at least an order of magnitude improvement, not just 5-10% improvement.
In my testing, the code I've provided here runs in about 85ms in my chrome dev console, and it takes about 300ms in a Node16 program.
-
There are zero libraries/dependencies here, and it must stay that way. I'm not going to just use an external date lib (or some huge timezone database, etc). And unfortuantely,
Intl
the long-hoped-for built-in JSTemporal
API (date/time capability upgrades) have still not landed -- seemingly stuck in stage-3. -
I deliberately have chosen a fixed timezone of "America/Chicago", which is where I am located, and where my app entirely runs. I don't need or care to support every possible timezone.
-
That said, even though I'm normalizing to "12:00:00.000" on a day, and only printing the date (not time) here for the purposes of testing, I do actually need to support DST, and stably ensure that every date has that same clock-time.
-
I'm intentionally detecting the TZ offset dynamically, because unlike normalizing to 12:00:00.000 (as here), the date/time such code might run could be at like 1:03am or at 4:09am, and depending on whether it's before or after the magic DST 2am changeover, there might be hour shifting if I didn't compute the TZ offset for every date.
Unfortunately, while modern browsers support the
timeZoneName: "longOffset"
feature (of Intl API), unfortunately Node 16 (which I'm stuck on) does not, so I need the fallback code for computing the tz-offset by counting hours/minutes between two timestamps. -
I have another dozen or so date utils like the ones above... and these utils are used many thousands of times across my app, both in Node (v16 -- no, I unfortunately cannot upgrade) and in the browser. I never noticed they were slow until I just recently did some heavier data aggregation (over several thousand records/iterations), and it turns out some of my loops, like a
reduce(..)
call (which do this kind of relative date math), are absurdly slow, like ~400ms to run a thousand iterations.I've narrowed it down that these date functions are the culprit, because when I comment them out (fake hard-code the data), the loops complete in less ~1ms.
Interesting exploration of this problem space with chatGPT:
https://chatgpt.com/share/6723a6d1-917c-8001-aee4-18f960fd1e53