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?
-
have a look here: stackoverflow.com/questions/43469583/es6-array-initialization/…Mario Vernari– Mario Vernari2020-09-03 12:07:46 +00:00Commented Sep 3, 2020 at 12:07
-
JavaScript has sparse arrays, meaning that this is not really possible.alesc– alesc2020-09-03 12:17:41 +00:00Commented 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.Jonas Wilms– Jonas Wilms2020-09-03 12:21:58 +00:00Commented Sep 3, 2020 at 12:21
Add a comment
|
1 Answer
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.
7 Comments
nicholaswmin
How does this improve performance however and by how much?
alesc
This creates a sparse array and doesn't allocate anything in advance. Meaning no performance improvement whatsoever.
Aplet123
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.
Aplet123
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.
|