array copy

JavaScript performance comparison

Revision 2 of this test case created by keville

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    var array = new Array(1, 2, 3, 4, 5);
};
</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-loop
function clone(arr) {
  var arr_clone = Array();
  for (var key in arr) {
    arr_clone[key] = arr[key];
  }
  return arr_clone;
}

var a2 = clone(array);
pending…
slice
var a2 = array.slice(0);
pending…
concat
var a2 = array.concat();
pending…
modified for-loop
function clone2 (arr) {
  var arr_clone = [];
  for (var i = 0, len = arr.length; i < len; ++i) {
    arr_clone[i] = arr[i];
  }
  return arr_clone;
}

var a2 = clone2(array);
pending…
push in for-loop
function clone3 (arr) {
  var arr_clone = [];
  for (var i = 0, len = arr.length; i < len; ++i) {
    arr_clone.push(arr[i]);
  }
  return arr_clone;
}

var a2 = clone3(array);
pending…
while-loop
function clone4 (arr) {
  var arr_clone = [],
      count = arr.length,
      index = 0;
  while (--count) {
    ++index;
    arr_clone[index] = arr[index];
  }
  return arr_clone;
}

var a2 = clone4(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