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?
By default
Uint8Array
,Uint16Array
andUint32Array
classes keep zeros as its values, so you don't need any complex filling techniques, just do:all elements of array
ary
will be zeros by default.SHORTEST
Array(n).fill(0)
(16 char), where
n
is size of array2018.10.28 i made performance comparison of 15 propositions from other answers. Tests was done on Mac OS X 10.13.6 High Sierra, on three browsers: Chrome 69.0.3497, Safari 12.0 (13606.2.11) and Firefox 63.0 (64 bit).
Result for n=100000
Below i show results for fastest browser (safari):
For all browsers the fastest solution was M - however it is not "typical array" (but very fast) - Safari 33.8k operations/second, Chrome 5.2k, FF 3.5k,
Fastest solutions for typical arrays:
The slowest solution:
Solution N works only on Firefox and Chrome.
Result for n=10
Fastest:
Slowest:
CONCLUSION
n
on Firefox) was Mlet a = new Float32Array(n)
(however is not typical array) - for it the fastest browser was Safari (for largen
>6x faster than Chrome, >9x faster than firefox)let a = Array(n).fill(0)
(fast and short code)You can perform test on your machine here.
There's always the phpjs solution, which you can find here:
http://phpjs.org/functions/array_fill/
I can't speak for the project (creating a library of javascript functions that mirrors the greater functionality of php) as a whole, but the few functions that I've personally pulled from there have worked like a champ.
My fastest function would be:
Using the native push and shift to add items to the array is much faster (about 10 times) than declaring the array scope and referencing each item to set it's value.
fyi: I consistently get faster times with the first loop, which is counting down, when running this in firebug (firefox extension).
I'm interested to know what T.J. Crowder makes of that ? :-)
Shortest for loop code
Safe var version
Didn't see this method in answers, so here it is:
In result you will get zero-valued array of length 200:
I'm not sure about the performance of this code, but it shouldn't be an issue if you use it for relatively small arrays.