0

Consider these 2 examples:

const length = 1000;
const array = [];
for (let i = 0; i < length; ++i) {
  array.push(true);
}

and

const length = 1000;
const array = new Array(length);
for (let i = 0; i < length; ++i) {
  array[i] = true;
}

They produce the same result (creating and filling an array), but in the second case the code tells the JS engine the expected array length.

Does it make sense to make a more complex code like in the second example? Does it give any advantages (e.g. performance improvements)?

Finesse
  • 9,793
  • 7
  • 62
  • 92
  • Another reason I do it is to share the knowledge. So, your downvotes don't bother me as long is the question is findable. – Finesse Jun 21 '21 at 06:24
  • Question is already a duplicate ¯\\_(ツ)_/¯ – Terry Jun 21 '21 at 06:25
  • @Terry I bet the community will benefit from the question. A similar situation happened at https://stackoverflow.com/q/40055654/1118709. It was downvoted and marked as duplicate first, but then got many upvotes. It happened because the question matches peoples' problems. – Finesse Jun 21 '21 at 06:29

1 Answers1

0

A test shows that the latter case (where the array length is specified beforehand) is 1.5–4 times faster. I've checked it in Safari 15, Firefox 89 and Chrome 91. So, yes, setting array length during the creation improves the performance.

Finesse
  • 9,793
  • 7
  • 62
  • 92
  • 1
    the right answer could be to use the constructor and allocate all needed space for the wanted length instead of having alwyas calculated space and change the array by having to reorganize the array. for speedy use, take an array with wanted length constructor and assign the value via index. – Nina Scholz Jun 21 '21 at 06:31