The question Is the Set.has() method O(1) and Array.indexOf O(n)? is listed as a duplicate of this one, which it isn't exactly (I've voted to re-open). I'll add these benchmarks here anyway, as the benchmarks on the replies to that question fail to show the full range of differences in performance between Set#has and Array#indexOf.
The following is all true as of Chrome 137:
You find that, for larger datasets, Set#has and Map#has are multiple orders of magnitude faster. Which is pretty consistent with what you'd expect for O(n) vs O(1) operations.
Meanwhile, Object#hasOwnProperty slightly outperforms Set#has and Map#has in all cases.
Benchmarking code
const [small, medium, large] = [1e2, 1e4, 1e6]
const configs = [
{ size: small, iterations: large },
{ size: medium, iterations: medium },
{ size: large, iterations: small },
]
for (const { size, iterations } of configs) {
let dummyVar
const arr = Array.from({ length: size }, (_, i) => String(i))
const obj = Object.fromEntries(arr.map(k => [k, true]))
const set = new Set(arr)
const map = new Map(Object.entries(obj))
const valsToTest = Array.from(
{ length: iterations },
(_, i) => String(Math.floor(Math.random() * size)),
)
const title = `dataset size: ${size.toLocaleString()}; iterations: ${iterations.toLocaleString()}`
console.log(`\n-> ${title}`)
for (const [target, method] of [
[arr, 'indexOf'],
[arr, 'includes'],
[set, 'has'],
[map, 'has'],
[obj, 'hasOwnProperty'],
]) {
const subtitle = `${target.constructor.name}#${method}`
console.time(subtitle)
for (const val of valsToTest) {
dummyVar = target[method](val)
}
console.timeEnd(subtitle)
}
}
My results (Chrome 137)
-> dataset size: 100; iterations: 1,000,000
Array#indexOf: 161.200ms
Array#includes: 176.600ms
Set#has: 49.600ms
Map#has: 41.200ms
Object#hasOwnProperty: 28.800ms
-> dataset size: 10,000; iterations: 10,000
Array#indexOf: 153.500ms
Array#includes: 144.800ms
Set#has: 0.700ms
Map#has: 0.600ms
Object#hasOwnProperty: 0.400ms
-> dataset size: 1,000,000; iterations: 100
Array#indexOf: 159.100ms
Array#includes: 159.200ms
Set#has: 0.200ms
Map#has: 0.100ms
Object#hasOwnProperty: 0.000ms