array copy

JavaScript performance comparison

Revision 9 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 = [1, 2, 3, 4, 5];
   
    function forinclone(arr) {
      var key, arr_clone = [];
      for (key in arr) {
        arr_clone[key] = arr[key];
      }
      return arr_clone;
    }
   
    function forclone(arr) {
      var i, len = arr.length,
          arr_clone = [];
      for (i = 0; i < len; i += 1) {
        arr_clone[i] = arr[i];
      }
      return arr_clone;
    }
    function revforclone(arr) {
      var i, len = arr.length,
          arr_clone = [];
      for (i = len - 1; i >= 0; i -= 1) {
        arr_clone[i] = arr[i];
      }
      return arr_clone;
    }
    function pushforclone(arr) {
      var i, len = arr.length,
          arr_clone = [];
      for (i = 0; i < len; i += 1) {
        arr_clone.push(arr[i]);
      }
      return arr_clone;
    }
   
    function whileclone(arr) {
      var len = arr.length,
          arr_clone = [];
      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…
push in for-loop
arr_clone = pushforclone(arr);
pending…
while-loop
arr_clone = whileclone(arr);
pending…
push
arr_clone = [];
arr_clone.push.apply(arr_clone, arr);
pending…
slice2
arr_clone = Array.prototype.slice.call(arr);
pending…
revForClone
arr_clone = revforclone(arr);
pending…
prototype push
arr_clone = [];
Array.prototype.push.apply(arr_clone, arr);
pending…
Array.apply
arr_clone = Array.apply(null, 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