Created
April 8, 2019 20:49
-
-
Save dodbrian/0350cd7a0aa3ce48452392a4cc6b45f8 to your computer and use it in GitHub Desktop.
Benchmarking JavaScript Arrays and Sets
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
let arr = [], set = new Set(), n = 1000000; | |
for (let i = 0; i < n; i++) { | |
arr.push(i); | |
set.add(i); | |
} | |
function checkArr(arr, value) { | |
return arr.indexOf(value); | |
} | |
function checkSet(set, value) { | |
return set.has(value); | |
} | |
console.log('\nFind a value:') | |
console.time('Array'); | |
result = checkArr(arr, 123123); | |
console.timeEnd('Array'); | |
console.time('Set'); | |
result = checkSet(set, 123123); | |
console.timeEnd('Set'); | |
console.log('\nAdd values:') | |
const numbersToAdd = n + 1001; | |
console.time('Array'); | |
for (let i = n + 1; i < numbersToAdd; i++) { | |
arr.push(i); | |
} | |
console.timeEnd('Array'); | |
console.time('Set'); | |
for (let i = n + 1; i < numbersToAdd; i++) { | |
set.add(i); | |
} | |
console.timeEnd('Set'); | |
console.log('\nRemove a value:') | |
const deleteFromArr = (arr, item) => { | |
let index = arr.indexOf(item); | |
return index !== -1 && arr.splice(index, 1); | |
}; | |
console.time('Array'); | |
deleteFromArr(arr, n); | |
console.timeEnd('Array'); | |
console.time('Set'); | |
set.delete(n); | |
console.timeEnd('Set'); | |
console.log('\nDedupe collection:') | |
const duplicateCollection = ['A', 'B', 'B', 'C', 'D', 'B', 'C']; | |
// If you want to turn the array into a Set | |
console.time('Set dedupe'); | |
let uniqueCollection = new Set(duplicateCollection); | |
console.timeEnd('Set dedupe'); | |
console.log(uniqueCollection) // Result: Set(4) {"A", "B", "C", "D"} | |
// If you want to keep your values in an array | |
console.time('Set dedupe into array'); | |
uniqueCollection = [...new Set(duplicateCollection)]; | |
console.timeEnd('Set dedupe into array'); | |
console.log(uniqueCollection) // Result: ["A", "B", "C", "D"] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment