Reputation: 5302
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.
Upvotes: 2
Views: 196
Reputation: 39532
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 []
.
Upvotes: 1