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 (somewhat logical). But some evidence, such as this, states that set traversals are much faster than array traversals, so I'm wondering if it's ever worthwhile to create a Set off an Array just to traverse it one or more times.
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.
forloop? it has no overheads ...array.forEachandset.forEach, not the set construction as well. Then you'll be able to say whether set iteration is faster or not. If you're not working with sets anyway and the set construction must be factored into the runtime, well, then it's probably not worth it.ArraySetis about 10% for less than 100 elements (which are tiny sets where performance hardly matters). The answer concludes that "a for-of loop [over an Array] is now always faster than a Set. The values iterator is roughly equal speed."!