Array unshift vs prepend

JavaScript performance comparison

Revision 13 of this test case created

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    function prependArray(value, oldArray) {
      var len = oldArray.length + 1, newArray = new Array(len);
      newArray[0] = value;
      for (var i = 1; i < len; ++i) {
        newArray[i] = oldArray[i - 1];
      }
      return newArray;
    }
   
    function prependArray2(value, oldArray) {
      return [value].concat(oldArray);
    }
   
    function prependArray3(value, oldArray) {
      var len = oldArray.length;
      ++oldArray.length;
      for (var i = len; i > 0; --i) {
        oldArray[i] = oldArray[i - 1];
      }
      oldArray[0] = value;
    }
    var a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
   
};
</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.unshift(0);
pending…
Prepend function
a = prependArray(0, a);
pending…
Unshift without mutation
a = a.slice(0);
a.unshift(0);
pending…
splice
a.splice(0,0,0);
pending…
Prepend2 function
a = prependArray2(0, a);
pending…
Prepend3 (mutate array)
prependArray3(0, a);
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