Last active
December 28, 2022 15:15
-
-
Save bnjm/5764ffe3de8332c8a7eed6fec0f4007b to your computer and use it in GitHub Desktop.
Array vs Set lookup benchmark
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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