Array cloning

JavaScript performance comparison

Revision 3 of this test case created

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    function cloneObject(object) {
      var clone = new object.constructor;
   
      for (var key in object) {
        clone[key] = object[key];
      }
   
      return clone;
    }
   
    function cloneArray1(array) {
      var clone = [];
   
      for (var i = 0; i < array.length; i++) {
        clone[i] = array[i];
      }
   
      return clone;
    }
   
    function cloneArray2(array) {
      var clone = [],
          len = array.length;
   
      for (var i = 0; i < len; i++) {
        clone[i] = array[i];
      }
   
      return clone;
    }
   
    function cloneArray3(array) {
      return array.concat();
    }
   
    function cloneArray4(array) {
      return array.slice();
    }
   
    function cloneArray5(array) {
      return array.slice(0);
    }
   
    function cloneArray6(array) {
      return array.filter(True);
    }
   
    function cloneArray7(array) {
      return array.map(Identity);
    }
   
    function cloneArray8(array) {
      return Array.apply([], array);
    }
   
    function cloneArray9(array) {
      return array.splice(0);
    }
   
    function cloneArray10(array) {
      return [].concat(array);
    }
   
    function True() {
      return true;
    }
   
    function Identity(v) {
      return v;
    }
    var array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
};
</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
for-in
cloneObject(array);
pending…
for
cloneArray1(array);
pending…
for (cached)
cloneArray2(array);
pending…
concat()
cloneArray3(array);
pending…
slice()
cloneArray4(array);
pending…
slice(0)
cloneArray5(array);
pending…
filter(True)
cloneArray6(array);
pending…
map(Identity)
cloneArray7(array);
pending…
Array.apply([], array)
cloneArray8(array);
pending…
splice(0)
cloneArray9(array);
pending…
concat new array
cloneArray10(array);
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