Performance Differences for Inserting Into an Array

I was bored and curious and decided to compare the performance among different ways of inserting an element into the middle of an array.

I tried three methods:

  1. Using Array.splice()
  2. Using Array.slice() and Array.concat()
  3. Using the ES6 rest operator

The winner was using the combination of Array.slice() and Array.concat()—at least in Chrome 47 and Firefox 43. 2nd place goes to using the ES6 rest operator. Check out the jsPerf.

There are also more performant ways to insert to the beginning and end of an array that aren't commonly used. In short, for adding to the beginning of an array, you may typically use existingArray.unshift(newItem), but [newItem].concat(existingArray) is way faster.

And for adding to the end of an array, you may typically use existingArray.push(newItem), but existingArray[existingArray.length] = newItem is faster.

Check out the jsPerf results for inserting to the beginning and to the end that were created by others.