Language/Javascript
[Javascript] Performance: Add large number of array elements to set.
yhcting
2020. 9. 10. 09:29
Test environment: Node 12.18.2 on Intel(R) Xeon(R) CPU E5-2697 v3 @ 2.60GHz
const SZ = 99999999
const l2a = [];
for (let i = 0; i < 10000; i++) {
const sub = [];
for (let j = 0; j < 10000; j++) {
sub.push(j);
}
l2a.push(sub);
}
let s = new Set();
let t = -Date.now();
for (const a of l2a) {
for (const n of a) {
s.add(n);
}
}
t += Date.now();
console.log('Takes: ', t);
const ta = [];
t = -Date.now();
for (const a of l2a) {
ta.concat(...a);
}
s = new Set(ta);
t += Date.now();
console.log('Takes: ', t);
Result is
Takes: 3070
Takes: 1665
Concating and expanding array are very fast comparing to calling a function(Set.add).