Array unshift vs prepend

JavaScript performance comparison

Revision 8 of this test case created by vincent piel

Preparation code

<script>
  var a;
  var prependArray = function(value, oldArray) {
   var i, len = oldArray.length + 1,
       newArray = new Array(len);
   newArray[0] = value;
   for (i = 0; i < len; ++i) {
    newArray.push(oldArray[i]);
   }
   return newArray;
  }

         var unshiftArray = function (arr, item) {
               var len=arr.length;
               while (len) { arr[len] = arr[len-1]; len--}
               arr[0] = item; };

</script>

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
Unshift
a = [1, 2, 3, 4];
a.unshift(0);
pending…
Prepend function
a = [1, 2, 3, 4];
prependArray(0, a);
pending…
Unshift without mutation
a = [1, 2, 3, 4];
a.slice(0).unshift(0);
pending…
manual unshift
a = [1, 2, 3, 4];
unshiftArray(a, 0);
 
pending…

Compare results of other browsers

Revisions

You can edit these tests or add even more tests to this page by appending /edit to the URL. Here’s a list of current revisions for this page:

0 comments

Add a comment