I have an array declared as
var arr = new Array();
Then i have an array of objects which are returned by Server. And each object in this array has three fields(always). I have to loop through this and add to the arr array conditionally.
Since this arr is not pre-allocated, it hits performance for large number in the main array.
Is there any way i can pre-allocate the arr array after i get the main response array so that i can avoid this performance issue?
Also how do i get the size of the object?
Thanks.
Suppose you have 10 objects, and you are going to pass three values from each object to an array. You can initialize your array with length 30 (10*3) by passing the integer 30 to the Array constructor as such:
var numObjects = 10;
var myArray = new Array(3*numObjects);
Please refer to my jsperf benchmark for a proof of the performance gained. In short summary, pre-sizing your array is ~25% faster in Firefox 38, ~81% faster in Chrome 42, and ~16% faster in Internet Explorer 11. Numbers will vary by the individual's experience who runs these benchmarks, but the trend will remain consistent. The optimal performance will result from pre-sizing your arrays.
http://jsperf.com/array-growth-dynamic-vs-preset
A more thorough discussion of this topic has occured here on SO at
How to initialize an array's length in javascript?
Thank whatever deity you believe in (or not) that Javascript does not have any direct access to memory allocation. That would have been truly horrible considering the quality of much of the JS littering the interwebs.
Javascript will by itself allocate memory to arrays on creation and reclaim the memory when it is garbage collected. Pre-Filling an array will have no positive effect on memory usage or performance.
Edit: I was wrong. See @ThisClark's answer.
MDN has a pretty good article on how memory management and GC work in javascript.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With