what's the fastest way to make short-lived arrays in Javascript?
i need to make this array very often. variable length, from a couple to a couple thousand. i don't know each length ahead of time. i also want to minimize memory allocations.
-
create a new array each time, use push() to add elements
-
create a new array each time, use [] and set the length at the end
-
preallocate one array, use [] and set the length
this way does the fewest allocations, and also turns out to be the fastest by a factor of ~2
yes, i know this is an unscientific microbenchmark.
done on a 2016 12" Macbook running node 6.4.0
$ node .
1000000 iters
499.38034
create and push: 3233.427ms
499.417887
create and set: 2852.723ms
499.49301
reuse and set: 1634.665ms
499.950513
create and push: 3152.367ms
499.235267
create and set: 2844.127ms
499.46329
reuse and set: 1646.972ms