Skip to content

Instantly share code, notes, and snippets.

@endel
Last active October 20, 2017 21:43
Show Gist options
  • Save endel/fe514f57f7bda2587ebc2ed18f1e51d0 to your computer and use it in GitHub Desktop.
Save endel/fe514f57f7bda2587ebc2ed18f1e51d0 to your computer and use it in GitHub Desktop.
Manual concat performs better than `Array.prototype.concat `.
import * as Benchmark from "benchmark";
// Array.prototype.concat()
const concat = function(...args: any[]) {
let arr = [1,2,3]
return arr.concat(args);
};
// "concat" manually, performs better
const manual = (...args: any[]) => {
let arr = [1,2,3]
let arr2 = arr.slice();
for(let i=0,l=args.length;i<l;i++) {
arr2.push(args[i]);
}
return arr2;
};
suite.add('concat', () => concat(4,5,6));
suite.add('manual concat', () => manual(4,5,6));
suite.on('cycle', (event: any) => console.log(String(event.target)))
suite.run();
concat x 2,728,238 ops/sec ±3.90% (77 runs sampled)
manual concat x 3,461,351 ops/sec ±1.57% (84 runs sampled)
@AndreasPizsa
Copy link

Wondering if apply would improve performance?

const manual = (...args: any[]) => {
    let arr = [1,2,3]
    let arr2 = arr.slice();
    Array.prototype.push(arr2, args)
    return arr2;
};

@AndreasPizsa
Copy link

AndreasPizsa commented Oct 20, 2017

Using arguments instead if ...args might help too since ...args creates a copy of arguments. So:

const manual = () => {
    let arr = [1,2,3]
    let arr2 = arr.slice();
    Array.prototype.push(arr2, arguments)
    return arr2;
};

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