Search code examples
javascriptarraysperformancev8

Should I pre-allocate an array or grow as I go


I have been trying to understand javascript better over the last few months. This has definitely made me want to get a Computer Science Degree. Anyways, I have sadly run into two related but conflicting points in relation to JavaScript.

According to this article, one should not prefill an array, but instead grow it when need be.

That sounded great and all, until I run into another article on wikipedia that stated that doing the above would be slow.

I am thinking of putting together some games from scratch, and being the code vegan that I am, plan on putting performance at the for front of my efforts. So is it better to have an array that grows or one that is pre-allocated? In HTML5 game development it is advised to use things such as object pools, which I tend to create using an array.


Solution

  • Rough guidelines:

    One that is pre-allocated is better. If you grow one with for instance push or pop the JS engine needs to do a lot of additinal steps.

    Even using an oversized array is way better than changing the size often. And you should operate on fixed size arrays whenever you can.

    Here you can find more information regarding this.

    Aray performance is Highly based on JS engine implementation:

    Because javascript is a specification not an implementatation different browsers have different versions of the Javascript engine. These versions are updated regularly to enhance speed and take different approaches on how to optimize this.

    When optimizing there are often tradeoffs between the speed of certain features including how arrays are manipulated/created. This means that the guidelines that I provided above might not be 100% accurate because one JS engine can have certain behaviour which the other JS engine lacks. This can cause differences in speed of manipulation/creation techniques on arrays.