4

In many programming languages an array can reserve a number of elements which allocates some amount of memory in advance to improve performance when adding elements to an array. Is there some equivalent in Javascript to do that kind of optimisation?

3
  • have a look here: stackoverflow.com/questions/43469583/es6-array-initialization/… Commented Sep 3, 2020 at 12:07
  • JavaScript has sparse arrays, meaning that this is not really possible. Commented Sep 3, 2020 at 12:17
  • If you look at the array size in different usecases, you'll see that engines might do that for you. How arrays look like in memory is not specified, and as such this is engine dependent and cannot be influenced by code. Commented Sep 3, 2020 at 12:21

1 Answer 1

1

Yes, you can use the array constructor with a single argument:

const arr = new Array(10); // now has 10 empty slots

Read more here. Both V8 and Spidermonkey (Chrome and Firefox's engines, respectively) receive a noticeable performance boost when preallocating the array. I have not tested on other engines.

Sign up to request clarification or add additional context in comments.

7 Comments

How does this improve performance however and by how much?
This creates a sparse array and doesn't allocate anything in advance. Meaning no performance improvement whatsoever.
While in theory there is no improvement, V8 is a magical beast that aggressively optimizes pre-allocated arrays. See the test suite here and my benchmarks (in chrome) here.
I have just tested with firefox (spidermonkey) and added the results to the album. Preallocating an array is still faster than not allocating an array, however first assigning to the 100th element is faster than preallocating an array. I'm going to continue testing to see if there's a way to get a uniform performance boost across both engines.
Both V8 and Spidermonkey (Chrome and Firefox's engines, respectively) receive a noticeable performance boost when preallocating the array. I have not tested on other engines.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.