both javascript code accomplish the same task merge the second array into the first one, i have read various blogs etc claming Option 2 is more memory efficient,
Is there a way or a tool to verify and see it for myself the memory usage in the Option 2 is lower ?
Option 1
//consume a lot of memory
var array1 = [1, 2, 3];
var array2 = [4, 5, 6];
console.log(array1.concat(array2));
Option 2
//reduce the memory usage
var array1 = [1, 2, 3];
var array2 = [4, 5, 6];
console.log(array1.push.apply(array1, array2));
i tried this approach https://www.valentinog.com/blog/node-usage/ node js code, not much helpful also tried https://github.com/paulirish/memory-stats.js dosent seems to work
CodePudding user response:
Your premise is wrong. Both scripts do not accomplish the same task.
Your first option allocates a new result array with 6 elements, and leaves both array1
and array2
untouched. (See the documentation for Array.prototype.concat()
.)
var array1 = [1, 2, 3];
var array2 = [4, 5, 6];
console.log(array1.concat(array2)); // [1, 2, 3, 4, 5, 6]
console.log(array1); // [1, 2, 3]
console.log(array2); // [4, 5, 6]
Your second option merges the contents of array2
into array1
. (See the documentation for Array.prototype.push()
.)
var array1 = [1, 2, 3];
var array2 = [4, 5, 6];
console.log(array1.push.apply(array1, array2)); // 6
console.log(array1); // [1, 2, 3, 4, 5, 6]
console.log(array2); // [4, 5, 6]
So the second option only requires a total of 9 array elements, while the first option requires 12. On a language level, option 2 is 25% more memory-efficient. How much memory is actually used by the JavaScript engine you're using is an implementation detail. In addition, contrived examples like these are typically not good candidates for reliable performance testing as the engine's JavaScript interpreter might apply various optimizations.