最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How to pre-allocate a dense array in Javascript? - Stack Overflow

programmeradmin3浏览0评论

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.

Share Improve this question edited May 23, 2017 at 11:54 CommunityBot 11 silver badge asked Jan 4, 2014 at 12:25 DomiDomi 24.7k19 gold badges104 silver badges132 bronze badges 2
  • 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
Add a ment  | 

2 Answers 2

Reset to default 4

100000 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 ..:)

发布评论

评论列表(0)

  1. 暂无评论