Skip to content

Instantly share code, notes, and snippets.

@lukaabra
Created August 3, 2020 11:23
Show Gist options
  • Save lukaabra/9cbd29e0a5018e2246b8840d73095a66 to your computer and use it in GitHub Desktop.
Save lukaabra/9cbd29e0a5018e2246b8840d73095a66 to your computer and use it in GitHub Desktop.
Compare the performance of checking whether an element is in an array before pushing it, and adding elements to a set in Node.
const {
performance
} = require('perf_hooks');
let arrayTime = [],
arrayLen = [],
setTime = [],
setLen = [];
let times = 1000
for (let i = 0; i < times; i++) {
t0 = performance.now();
let a = []
for (let j = 0; j < 10000; j++) {
let x = (Math.random() * 10000).toFixed(0);
if (!(a.includes(x))) a.push(x)
}
t1 = performance.now();
arrayTime.push((t1 - t0).toFixed(5));
arrayLen.push(a.length)
}
let averageArrayTime = arrayTime.reduce((avg, value, _, {
length
}) => {
return avg + value / length;
}, 0);
let averageArraySize = arrayLen.reduce((avg, value, _, {
length
}) => {
return avg + value / length;
}, 0);
console.log("==============================")
console.log("ARRAY TIME: \t" + averageArrayTime.toFixed(2) + " ms");
console.log("ARRAY LEN: \t" + averageArraySize.toFixed(0) + " elements");
console.log("==============================")
for (let i = 0; i < times; i++) {
t2 = performance.now();
let b = new Set()
for (let j = 0; j < 10000; j++) {
let y = (Math.random() * 10000).toFixed(0);
b.add(y);
}
t3 = performance.now();
setTime.push((t3 - t2).toFixed(5));
setLen.push(b.size)
};
let averageSetTime = setTime.reduce((avg, value, _, {
length
}) => {
return avg + value / length;
}, 0);
let averageSetSize = setLen.reduce((avg, value, _, {
length
}) => {
return avg + value / length;
}, 0);
console.log("SET TIME: \t" + averageSetTime.toFixed(2) + " ms");
console.log("SET LEN: \t" + averageSetSize.toFixed(0) + " elements");
console.log("==============================")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment