Last active
October 20, 2017 21:43
-
-
Save endel/fe514f57f7bda2587ebc2ed18f1e51d0 to your computer and use it in GitHub Desktop.
Manual concat performs better than `Array.prototype.concat `.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
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
Wondering if
apply
would improve performance?