2

Is there a performance boost to predefining the length of a Javascript array when pushing items into that array?

For instance, suppose you're doing this:

var item1 = "apple",
    item2 = "orange",
    item3 = "sports car"; // Because I said so, that's why.

var myArray = [];  // Empty array with initial length of 0

myArray.push(item1);
console.log(myArray.length) // 1

myArray.push(item2);
console.log(myArray.length) // 2

myArray.push(item3);
console.log(myArray.length) // 3

In the above code the length of myArray is recalculated on each push. Alternatively;

var item1 = "apple",
item2 = "orange",
item3 = "sports car";

var myArray = Array(3) // Assume we already know exactly how many items will be added
myArray[0] = item1;
console.log(myArray.length) // 3

myArray[1] = item2;
console.log(myArray.length) // 3

myArray[2] = item3;
console.log(myArray.length) // 3

My question is this, when you explicitly assign a value to a pre-existing slot within an array is the length property of that array still re-evaluated. If not, does sidestepping that process yield faster array population?

It should go without saying that this is more of a theoretical exercise than an actual real-world problem.

monners
  • 5,174
  • 2
  • 28
  • 47
  • 1
    Some people doing benchmarks on a very related question: http://stackoverflow.com/questions/1295584/most-efficient-way-to-create-a-zero-filled-javascript-array – Thilo Aug 02 '13 at 03:40
  • Array literals are faster because you don't need to invoke the constructor (or run an extra function), but I'm not sure about your particular question. I doubt it makes a _real_ difference. – elclanrs Aug 02 '13 at 03:41
  • I would guess that setting the length beforehand might speed up the insertion later. – Ja͢ck Aug 02 '13 at 03:44
  • I suppose the length property is not re-evaluated, it will always be 3 ! I mean if you don''t add `myArray[2] = item3;` still the length will show 3 not 2, since the 3rd slot will take a default value –  Aug 02 '13 at 04:08
  • 3
    Jsperf is great for real world tests of this sort of thing. Your test.. http://jsperf.com/pre-allocated-arrays/6 – rlb Aug 02 '13 at 06:23

1 Answers1

1

According to this JSPerf, predefining length is faster, by quite a bit.

It should be noted that new Array() syntax isn't exactly considered best practice. If you absolutely need to squeeze every last bit of performance, consider this. Otherwise, make life easy for you and all the developers who touch your code, use [].

SomeKittens
  • 38,868
  • 19
  • 114
  • 143
  • It's not quite comparing apples to apples there, since your second example isn't using push, which is typically a bit slower than just assigning the index. It would be interesting to see all variations (defined/not defined length, push/assign by index). But an interesting result. – Evan Trimboli Feb 01 '14 at 00:58
  • @EvanTrimboli I'll add a non-push version. – SomeKittens Feb 01 '14 at 00:59