I recently took on the task of re-writing several open source JavaScript repositories I maintain to take advantage of recent optimizations in the JavaScript v8 engine.
Some of these optimization involved using built-in classes like Map
and Set
instead of arrays. When I first implemented the libraries, either Map
and Set
were not available or they provided no real performance benefit over Array
.
Other optimizations have included changing the order of array iteration or loop types. At a micro-optimization level, sometimes looping backwards is faster than forwards and while
can be faster than for
.
When working with set operations on arrays, I uncovered a fundamental paradigm shift that provides performance boosts of 1x, 2x or even orders of magnitude.
Paradigm Shift
For many set operations, the ultimate members of a set can be known prior to the complete set being assembled. For instance, when asking for a union, every item in every collection (Sets or Arrays) will be in the final result at least and at most once. So why not return all the items in the first collection in rapid succession and then the items in the subsequent collections one after the other so long as they have not already been returned?