What is the most efficient way to create an arbitrary length zero filled array in JavaScript?
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- void before promise syntax
- Keeping track of variable instances
- Can php detect if javascript is on or not?
ES6 solution:
This
concat
version is much faster in my tests on Chrome (2013-03-21). About 200ms for 10,000,000 elements vs 675 for straight init.Bonus: if you want to fill your array with Strings, this is a concise way to do it (not quite as fast as
concat
though):I just use :
The way I usually do it (and is amazing fast) is using
Uint8Array
. For example, creating a zero filled vector of 1M elements:I'm a Linux user and always have worked for me, but once a friend using a Mac had some non-zero elements. I thought his machine was malfunctioning, but still here's the safest way we found to fix it:
Edited
Chrome 25.0.1364.160
Firefox 20.0
Missing the most important test (at least for me): the Node.js one. I suspect it close to Chrome benchmark.
If you need to create many zero filled arrays of different lengths during the execution of your code, the fastest way I've found to achieve this is to create a zero array once, using one of the methods mentioned on this topic, of a length which you know will never be exceeded, and then slice that array as necessary.
For example (using the function from the chosen answer above to initialize the array), create a zero filled array of length maxLength, as a variable visible to the code that needs zero arrays:
Now slice this array everytime you need a zero filled array of length requiredLength < maxLength:
I was creating zero filled arrays thousands of times during execution of my code, this speeded up the process tremendously.