array copy

JavaScript performance comparison

Revision 10 of this test case created

Info

Previous tests were also testing fn construction, not just pure array construction. This differs from http://jsperf.com/slice-vs-copy/ in that these are all function invocations, not just inline (which is basically always faster under 10 members).

Pre-allocating the target array length, see http://jsperf.com/pre-allocationg-vs-literal. Note, the length of the array matters greatly, see http://jsperf.com/slice-vs-copy/ in the revisions/notes.

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    var arr = new Array(1, 2, 3, 4, 5);
   
    function forinclone(arr) {
      var key, arr_clone = new Array(arr.length);
      for (key in arr) {
        arr_clone[key] = arr[key];
      }
      return arr_clone;
    }
   
    function forclone(arr) {
      var i, len = arr.length,
          arr_clone = new Array(len);
      for (i = 0; i < len; i += 1) {
        arr_clone[i] = arr[i];
      }
      return arr_clone;
    }
   
    function forclone2(arr) {
      var i, len = arr.length,
          arr_clone = new Array(len);
      for (i = 0; i !== len; ++i) {
        arr_clone[i] = arr[i];
      }
      return arr_clone;
    }
   
    function forclone3(arr) {
      var i, len = arr.length,
          arr_clone = new Array(len);
      arr_clone.concat(arr);
      return arr_clone;
    }
   
    function whileclone(arr) {
      var len = arr.length,
          arr_clone = new Array(len);
      while (len--) {
        arr_clone[len] = arr[len];
      }
      return arr_clone;
    }
};
</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
arr_clone = forinclone(arr);
pending…
slice
arr_clone = arr.slice();
pending…
concat
arr_clone = arr.concat();
pending…
modified for-loop
arr_clone = forclone(arr);
pending…
forclone2
arr_clone = forclone2(arr);
pending…
forclone3
arr_clone = forclone3(arr);
pending…
push
arr_clone = [];
arr_clone.push.apply(arr_clone, arr);
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