Array cloning

JavaScript performance comparison

Revision 5 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(a) {
      var newObj = [];
      for(var i in a){
        if(i == 'clone') continue;
        if(a[i] && typeof a[i] == "object") {
          newObj[i] = cloneObject9(a[i]);
        }else{
          newObj[i] = a[i];
        };
      }
      return newObj;
    };
   
    function cloneArray10(array) {
      return [].concat(array);
    }
   
    function cloneArray11(array) {
      return array.slice(0,array.length);
    }
   
    function cloneArray12(array) {
      return JSON.parse(JSON.stringify(array));
    }
   
    function cloneArray13(array) {
      var b = new Array();
      b.push.apply(b,array);
      return b;
    };
   
    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…
loop with detect sub array
cloneArray9(array);
pending…
concat new array
cloneArray10(array);
pending…
slice(0, array.length)
cloneArray11(array);
pending…
JSON
cloneArray12(array);
pending…
push.apply
cloneArray13(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