Skip to content

Instantly share code, notes, and snippets.

@bnjm
Last active December 28, 2022 15:15
Show Gist options
  • Save bnjm/5764ffe3de8332c8a7eed6fec0f4007b to your computer and use it in GitHub Desktop.
Save bnjm/5764ffe3de8332c8a7eed6fec0f4007b to your computer and use it in GitHub Desktop.
Array vs Set lookup benchmark
function bench(cb, arg, label) {
console.time(label)
cb(arg)
console.timeEnd(label)
}
function createArray(length) {
return Array.from({ length }, (_, i) => i)
}
function nestedSetSearch(array) {
const set = new Set(array)
return array.filter(item => set.has(item))
}
function nestedArraySearch(array) {
return array.filter(item => array.includes(item))
}
const arrayLengths = [100, 1_000, 10_000, 100_000]
function run() {
arrayLengths.forEach(length => {
bench(nestedArraySearch, createArray(length), `array ${length}`.padEnd(14))
})
arrayLengths.forEach(length => {
bench(nestedSetSearch, createArray(length), `set ${length}`.padEnd(14))
})
}
run()
/*
MacBook Air 2020, Chrome 108
array 100 : 0.056884765625 ms
array 1000 : 0.280029296875 ms
array 10000 : 15.889892578125 ms
array 100000 : 543.7998046875 ms
set 100 : 0.045166015625 ms
set 1000 : 0.087158203125 ms
set 10000 : 0.864990234375 ms
set 100000 : 8.87109375 ms
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment