Skip to content

Instantly share code, notes, and snippets.

@DronRathore
Created August 20, 2015 13:01
Show Gist options
  • Save DronRathore/be4d40925ecda3451ac4 to your computer and use it in GitHub Desktop.
Save DronRathore/be4d40925ecda3451ac4 to your computer and use it in GitHub Desktop.
Array Init vs Array.push
/*
Adding values in array at init using variables is faster
then processing individual entity
*/
function A(options){
var a = [ “something” + options.A + “more”, “second elem” + options.B + “Yo!”]
return A;
}
function B(options){
var a = [];
a.push( “something” + options.A + “more”);
a.push(“second elem” + options.B + “Yo!”);
return A;
}
@DronRathore
Copy link
Author

For a set of 100000 calls on nodejs-v12 stats are

Function A: 6 ~ 8ms
Function B: 11 ~ 15ms

Explanation is quite simple Function invocation costs the engine to jump context, but JS Engine does optimise push calls by inlining them, still the inlined function also has to flatten the arguments and then push back the length property on the return stack of the context.

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