Skip to content

Instantly share code, notes, and snippets.

@andrey-legayev
Created November 2, 2019 22:08
Show Gist options
  • Save andrey-legayev/142ad2e2a00980e6da3776d40636fbfe to your computer and use it in GitHub Desktop.
Save andrey-legayev/142ad2e2a00980e6da3776d40636fbfe to your computer and use it in GitHub Desktop.
JS Benchmark: test performance of Set()
function test(size, iterations) {
let data_array = [];
let data_obj = {};
for (let i = 0; i < size; i++) {
let rnd = Math.floor(Math.random() * size * 10);
data_array.push(rnd);
data_obj[rnd] = true;
}
let data_set = new Set(data_array);
let t = performance.now();
for (let j = 0; j < iterations; j++) {
let x = data_array.indexOf(j) !== -1;
}
let t1 = performance.now() - t;
t = performance.now();
for (let j = 0; j < iterations; j++) {
let x = data_obj[j];
}
let t2 = performance.now() - t;
t = performance.now();
for (let j = 0; j < iterations; j++) {
let x = data_set.has(j);
}
let t3 = performance.now() - t;
console.log([size, iterations, t1/1000, t2/1000, t3/1000].join(", "));
}
console.log("# Array Size, Iterations, in array, in object, in set");
for (let i = 1; i <= 10000; i *= 10) {
test(i, 100000)
}
@andrey-legayev
Copy link
Author

I'm surprised: set.has() is a bit faster than object[key]
Tested in Node.js 10 and Chrome 78

# Array Size, Iterations, in array, in object, in set
1, 100000, 0.004294999991543591, 0.0018899999558925629, 0.0028300000121816993
10, 100000, 0.0055049999500624835, 0.00004499999340623617, 0.001445000001695007
100, 100000, 0.014035000000149012, 0.003824999963399023, 0.0015850000199861825
1000, 100000, 0.08825999998953193, 0.0030350000015459955, 0.0015300000086426735
10000, 100000, 0.8473499999963678, 0.005385000025853515, 0.0016049999976530671

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment