I came across the following benchmarks: https://jsperf.com/array-includes-and-find-methods-vs-set-has
If you'll execute it, you'll see that map.has is by far the most efficient way of finding an item in a collection in the browser.
I also recreated this test in Node using benchmarks.js, and got the following results:
Node 9.4.0:
set.has x 6,454,428 ops/sec ±1.25% (90 runs sampled)
map.has x 64,519,657 ops/sec ±0.95% (86 runs sampled)
arr.includes x 11,415,721 ops/sec ±1.41% (87 runs sampled)
arr.indexOf x 11,344,587 ops/sec ±1.39% (87 runs sampled)
arr.find x 1,579,635 ops/sec ±1.09% (92 runs sampled)
Fastest is map.has
Node 6.2.0:
set.has x 16,677,473 ops/sec ±1.35% (86 runs sampled)
map.has x 15,089,503 ops/sec ±1.35% (85 runs sampled)
arr.includes x 1,345,019 ops/sec ±1.31% (89 runs sampled)
arr.indexOf x 15,943,213 ops/sec ±4.40% (80 runs sampled)
arr.find x 1,423,994 ops/sec ±2.05% (82 runs sampled)
Fastest is set.has,arr.indexOf
These results are very surprising for me, does anyone know:
How come
map.hasis 10 times faster thanset.hasand almost 6 times faster thanarray.indexOf?In Node 6,
includesseems to be much slower thanindexOf, andarr.find(val => val === 1)is the same asarr.includes(1). Why?set.hasseems to be slower in Node 9 than it used to be in Node 6, why is that?
Setis implemented as a hash set, which doesn't need to do linear search? That's the whole purpose of using it over a list structure.hasofMapandindexOfdo two complelty differnt things.indexOfsearches for a value (that might exists multible times in an array). Andhasfor ankeythat has to be unique.Map.hasis ten times faster thanSet.has?Map.hasis way faster thanSet.has?6.2.0forhasis what I would expect. At the end of 2017 they closed JS Maps and Sets Performance, but when those changes in v8 are included into node Performance regression in v8.10 and v9.0 for Maps with object keys depends on when node updates v8.