For large arrays (i.e. 1M elements), is it faster to create and iterate over a Set (from an Array) than an Array – if you just need a single or two iterations to occur ever and performance is the only requirement (no need for deduping the array etc)?
Consider the following two scenarios for illustration of what I mean:
const array = Array.from({length: 1_000_000});
const methodOne = () => { array.forEach(() => {...}) }
const methodTwo = () => { const set = new Set(array); set.forEach(() => {...}) }
end of program
In browser when timed, this goes in favor of the first approach, but that comes into conflict with the knowledge that sets are faster to iterate.
I’m guessing it boils down to the exact implementation of the Set constructor, which I can’t find and whether it needs to traverse the Array in order to create a Set. I’m aware that Set is implemented as an ordered hash table of some sort.