I hate benchmarking code, just like any human (which, at this point, most viewers of this probably aren’t ¯\_(ツ)_/¯). It is much more fun to pretend that your caching of a value increased performance 1000% rather than testing to see what it did. Alas, benchmarking in JavaScript is still necessary, especially as JavaScript is used (when it shouldn’t be?) in more performance-sensitive applications. Unfortunately, due to many of its core architectural decisions, JavaScript doesn’t make benchmarking any easier.
For those unfamiliar with the wizardry of modern scripting languages like JavaScript, their architecture can be pretty complex. Instead of only running code through an interpreter that immediately spits out instructions, most JavaScript engines utilize an architecture more similar to a compiled language like C—they integrate multiple tiers of “compilers”.
Each of these compilers offers a different tradeoff between compilation time and runtime performance, so the user doesn’t need to spend compute optimizing code that is rarely run while taking advantage of the more advanced compiler’s performance benefits for the code that is run most often (the “hot paths”). There are also some other complications that arise when using optimizing compilers that involve fancy programming words like “function monomorphism”, but I will spare you and avoid talking about that here.