In the case of a JS array, it's possible to create one with predefined length. If we pass the length to the constructor, like new Array(itemCount)
, a JS engine could pre-allocate memory for the array, so it won't be needed to reallocate it while new items are added to the array.
Is it possible to pre-allocate memory for a Map
or Set
? It doesn't accept the length in the constructor like array does. If you know that a map will contain 10 000 items, it should be much more efficient to allocate the memory once than reallocate it multiple times.
Here is the same question about arrays.
There is discussion in the comments, whether the predefined array size has an impact on the performance or not. I've created a simple test to check it, the result is:
- Chrome - filling an array with a predefined size is about 3 times faster
- Firefox - there is no much difference, but the array with predefined length is a little bit faster
- Edge - filling of a predefined size array is about 1.5 times faster
There is a suggestion to create the entries array and pass it to the Map, so the map can take the length from the array. I've created such test too, the result is:
- Chrome - construction of a map which accepts entries array is about 1.5 times slower
- Firefox - there is no difference
- Edge - passing of entries array to the Map constructor is about 1.5 times faster