X

JavaScript Array Push Performance

This is a short response I wrote to a question on /r/javascript. The user who asked it was curious whether there would be any performance difference between adding elements to a JavaScript array by calling push, or manually adding a new object to an array by making a call like myArray[myArray.length] = obj. Let’s take a look at the ECMAScript specification to see what it says.  

In the case of Array.prototype.push, the JS runtime must first call toObject on the argument passed to push. It must also do a bit of work to handle the case where more than one item was passed to push, since you are allowed to make a call like this: abc.push(1,2,3). After from calling toObject and checking how many arguments were provided, it then goes through each one and does a regular property set call, which ends doing the same as myArray[myArray.length] = obj.

If you’re only adding one thing to your array, you may as well call push, since it is easier to read and the toObject call and args length check is going to make an immeasurably small difference to execution time.

If you’re adding multiple things to your array, then call myArray.push(...things). because when you do that, the JS engine’s compiled C++ will handle all of the iteration, instead of thunking back and forth between native code and JavaScript if you’re looping through yourself and calling push every time. In reality, with all of the optimization and JITing that modern JS engines do, looping through yourself probably isn’t all that much slower than passing everything to pushat once. I haven’t tested this to verify, though.

Categories: JavaScript
Ryan Peden: