Last active
March 7, 2022 20:16
-
-
Save snewcomer/ac7bffd8c79ddedf54df107bf4a64399 to your computer and use it in GitHub Desktop.
array.includes vs set.has
This file contains hidden or 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
const makeArray = (size) => [...Array(size)].map(() => size); | |
const small = makeArray(1000); | |
const medium = makeArray(10000000); | |
const large = makeArray(100000000); | |
const solution1 = (arr) => { | |
arr.includes(arr.length - 1); | |
}; | |
const solution2 = (arr) => { | |
const set = new Set(arr); | |
set.has(arr.length - 1); | |
}; | |
let t1 = process.hrtime(); | |
solution1(small); | |
let t2 = process.hrtime(t1); | |
console.info('Small: Array.includes execution time (hr): %ds %dms', t2[0], t2[1] / 1000000); | |
t1 = process.hrtime(); | |
solution2(small); | |
t2 = process.hrtime(t1); | |
console.info('Small: Set.has execution time (hr): %ds %dms', t2[0], t2[1] / 1000000); | |
t1 = process.hrtime(); | |
solution1(medium); | |
t2 = process.hrtime(t1); | |
console.info('Medium: Array.includes execution time (hr): %ds %dms', t2[0], t2[1] / 1000000); | |
t1 = process.hrtime(); | |
solution2(medium); | |
t2 = process.hrtime(t1); | |
console.info('Medium: Set.has execution time (hr): %ds %dms', t2[0], t2[1] / 1000000); | |
t1 = process.hrtime(); | |
solution1(large); | |
t2 = process.hrtime(t1); | |
console.info('Large: Array.includes execution time (hr): %ds %dms', t2[0], t2[1] / 1000000); | |
t1 = process.hrtime(); | |
solution2(large); | |
t2 = process.hrtime(t1); | |
console.info('Large: Set.has execution time (hr): %ds %dms', t2[0], t2[1] / 1000000); |
Author
snewcomer
commented
Mar 7, 2022
•
Without Set initialization
const makeArray = (size) => [...Array(size)].map(() => size);
const small = makeArray(10000);
const medium = makeArray(10000000);
const large = makeArray(100000000);
const solution1 = (arr, type) => {
let t1 = performance.now();
arr.includes(arr.length - 1)
let t2 = performance.now();
console.warn(`${type}: Array.includes: ${t2 - t1}ms`);
}
const solution2 = (arr, type) => {
const set = new Set(arr)
let t1 = performance.now();
set.has(arr.length-1)
let t2 = performance.now();
console.warn(`${type}: Set.has: ${t2 - t1}ms`);
}
solution1(small, 'Small');
solution2(small, 'Small');
solution1(medium, 'Medium');
solution2(medium, 'Medium');
solution1(large, 'Large');
solution2(large, 'Large');
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment