Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pre-allocate a dense array in Javascript?

When using the new Array(size) ctor, if size is not a constant, JS seems to create a sparse array in some browsers (at least in Chrome), causing access to be much slower than when using the default ctor, as shown here.

That is exactly the opposite of what I want: I pre-allocate an array of given size to avoid dynamic re-allocation and thereby improving performance. Is there any way to achieve that goal?

Please note that this question is not about the ambiguity of the new Array(size) ctor. I posted a recommendation on that here.

like image 970
Domi Avatar asked Jan 04 '14 12:01

Domi


2 Answers

100000 is 1 past the pre-allocation threshold, 99999 still pre-allocates and as you can see it's much faster

http://jsperf.com/big-array-initialize/5

like image 60
Esailija Avatar answered Oct 07 '22 06:10

Esailija


Pre-allocated vs. dynamically grown is only part of the story. For preallocated arrays, 100,000 just so happens to be the threshold where V8 decides to give you a slow (a.k.a. "dictionary mode") array.

Also, growing arrays on demand doesn't allocate a new array every time an element is added. Instead, the backing store is grown in chunks (currently it's grown by roughly 50% each time it needs to be grown, but that's a heuristic that might change over time).

You can find more information ..here.Thanks ..:)

like image 37
Avinash Babu Avatar answered Oct 07 '22 07:10

Avinash Babu