Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pre-allocate memory to array of objects

Tags:

javascript

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.

like image 1000
aneeshere Avatar asked May 20 '15 14:05

aneeshere


2 Answers

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?

like image 85
ThisClark Avatar answered Oct 01 '22 22:10

ThisClark


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.

like image 39
max Avatar answered Oct 01 '22 22:10

max