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 remendation on that here.
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 remendation on that here.
- You mean, no elements will be pushed in or popped out of the Array? – thefourtheye Commented Jan 4, 2014 at 12:30
- jsperf./pre-allocated-arrays/6 – Avinash Babu Commented Jan 4, 2014 at 12:33
2 Answers
Reset to default 4100000 is 1 past the pre-allocation threshold, 99999 still pre-allocates and as you can see it's much faster
http://jsperf./big-array-initialize/5
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 ..:)