Array unshift vs prepend

JavaScript performance comparison

Revision 9 of this test case created

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 unshiftArrayWhileBackward = function(arr, item) {
      var len = arr.length;
      while (len) {
        arr[len] = arr[len - 1];
        len--
      }
      arr[0] = item;
      return arr
      };

  var unshiftArrayWhileForward = function(arr, item) {
      var len = arr.length;
      var i = -1;
      var temp = item;
      var temp2 = item;
      while (++i < len) {
        temp = temp2;
        temp2 = arr[i];
        arr[i] = temp;
      }
      arr[len] = temp2;
      return arr
      };

  var unshiftArrayForBackward = function(arr, item) {
      var len = arr.length;
      for (; len;) {
        arr[len] = arr[len - 1];
        len--
      }
      arr[0] = item;
      return arr
      };

  var unshiftArrayForForward = function(arr, item) {
      var len = arr.length;
      var temp = item;
      var temp2 = item;
      for (var i = 0; i < len; i++) {
        temp = temp2;
        temp2 = arr[i];
        arr[i] = temp;
      }
      arr[len] = temp2;
      return arr
      };
</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…
Concat
a = [1, 2, 3, 4];
[0].concat(a);
pending…
Manual unshift while loop backward
a = [1, 2, 3, 4];
unshiftArrayWhileBackward(a, 0);
pending…
Manual unshift while loop forward
a = [1, 2, 3, 4];
unshiftArrayWhileForward(a, 0);
pending…
Manual unshift for loop backward
a = [1, 2, 3, 4];
unshiftArrayForBackward(a, 0);
pending…
Manual unshift for loop forward
a = [1, 2, 3, 4];
unshiftArrayForForward(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