Array Cloning

JavaScript performance comparison

Test case created by Chris West

Preparation code


      
      <script>
Benchmark.prototype.setup = function() {
  function loopClone(a) {
    for (var i = 0, l = a.length, r = new Array(l); i < l; i++) {
      if (i in a) {
        r[i] = a[i];
      }
    }
    return r;
  }
  
  function reverseLoopClone(a) {
    for (var i = a.length, r = new Array(i); i--;) {
      if (i in a) {
        r[i] = a[i];
      }
    }
    return r;
  }
  
  var hasOwnProperty = {}.hasOwnProperty;
  
  function loopPropClone(a) {
    for (var i = 0, l = a.length, r = new Array(l); i < l; i++) {
      if (hasOwnProperty.call(a, i)) {
        r[i] = a[i];
      }
    }
    return r;
  }
  
  function reverseLoopPropClone(a) {
    for (var i = a.length, r = new Array(i); i--;) {
      if (hasOwnProperty.call(a, i)) {
        r[i] = a[i];
      }
    }
    return r;
  }
  
  function slice(o) {
    return Array.prototype.slice.call(o);
  }
  
  function makeArray(o) {
    try {
      return Array.prototype.slice.call(o);
    } catch (e) {}
    
    for (var i = 0, l = o.length, a = new Array(i); i < l; i++) {
      if (i in o) {
        a[i] = o[i];
      }
    }
    return a;
  }
  
  var elems = document.documentElement.getElementsByTagName('*');
  
  var arr1 = new Array(10);
  arr1[5] = 5;
  
  var arr2 = new Array(100);
  arr1[50] = 50;
  
  var arr3 = new Array(1000);
  arr1[500] = 500;
  
  var arr4 = new Array(10000);
  arr1[9999] = 9999;
  
  var arr5 = [/a/, 'sdf', null, undefined, 3, 6.2, RegExp, {}, []];
  
  var objects = [elems, arr1, arr2, arr3, arr4, arr5];

};
</script>

Test runner

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

Java applet disabled.

Testing in CCBot 2.0.0 / Other 0.0.0
Test Ops/sec
slice with fallback to for loop clone
for (var i = 0, l = objects.length; i < l; i++) {
  var result = makeArray(objects[i]);
}
pending…
for loop clone
for (var i = 0, l = objects.length; i < l; i++) {
  var result = loopClone(objects[i]);
}
pending…
reverse for loop clone
for (var i = 0, l = objects.length; i < l; i++) {
  var result = reverseLoopClone(objects[i]);
}
pending…
for loop clone (with hasOwnProperty)
for (var i = 0, l = objects.length; i < l; i++) {
  var result = loopPropClone(objects[i]);
}
pending…
reverse for loop clone (with hasOwnProperty)
for (var i = 0, l = objects.length; i < l; i++) {
  var result = reverseLoopPropClone(objects[i]);
}
pending…
slice
for (var i = 0, l = objects.length; i < l; i++) {
  var result = slice(objects[i]);
}
pending…

You can edit these tests or add even more tests to this page by appending /edit to the URL.

Compare results of other browsers

0 Comments