Skip to content

Instantly share code, notes, and snippets.

@guyellis
Created August 11, 2017 04:24
Show Gist options
  • Save guyellis/674900b9678b9c9aa28b9a6f2153bf24 to your computer and use it in GitHub Desktop.
Save guyellis/674900b9678b9c9aa28b9a6f2153bf24 to your computer and use it in GitHub Desktop.
A speed test between using concat() and push() when reducing an array of arrays to a single array
// Which is faster depends on which version of Node you're using.
// See the bottom for the results.
const iterations = 1000000;
const arrayOfTen = [...Array(10).keys()];
const arrayOfArrays = [...Array(10).keys()].map(() => arrayOfTen);
const NS_PER_SEC = 1e9;
function a() {
for (let i = 1; i < iterations; i++) {
arrayOfArrays.reduce((acc, innerArray) => {
acc.push(...innerArray);
return acc;
}, []);
}
}
function b() {
for (let i = 1; i < iterations; i++) {
arrayOfArrays.reduce((acc, innerArray) => acc.concat(innerArray), []);
}
}
let time = process.hrtime();
a();
let diff = process.hrtime(time);
console.log(`Test A took ${diff[0] * NS_PER_SEC + diff[1]} nanoseconds`);
time = process.hrtime();
b();
diff = process.hrtime(time);
console.log(`Test B took ${diff[0] * NS_PER_SEC + diff[1]} nanoseconds`);
// Results:
// $ node - v
// v8.3.0
// Test A took 653492137 nanoseconds
// Test B took 1968402981 nanoseconds
// Test A took 649657112 nanoseconds
// Test B took 1961882017 nanoseconds
// Test A took 635760306 nanoseconds
// Test B took 1862738481 nanoseconds
// $ node - v
// v6.11.2
// Test A took 10184520458 nanoseconds
// Test B took 3388628276 nanoseconds
// Test A took 9476108180 nanoseconds
// Test B took 3162485775 nanoseconds
// Test A took 9456780696 nanoseconds
// Test B took 3167964775 nanoseconds
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment