JavaScript Array Copy Comparison

JavaScript performance comparison

Revision 2 of this test case created by Luis Cantero

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    Object.deepCopy = function(obj) {
      if (typeof obj !== "object") return obj;
   
      var newObj = (obj instanceof Array) ? [] : {};
      for (i in obj) {
        if (obj[i] && typeof obj[i] == "object") newObj[i] = Object.clone(obj[i]);
        else newObj[i] = obj[i];
      }
      return newObj;
    };
   
    var a = [];
    var i = 100;
    while (i--)
        a.push(i);
   
    var len = a.length;
};
</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
Copy by slice
var b = a.slice(0);
pending…
Copy by splice
var b = a.splice(0);
pending…
Copy by concat
var b = a.concat();
pending…
Copy by stringify & eval
var b = eval(JSON.stringify(a));
pending…
Copy by iterator
var b = Object.deepCopy(a);
pending…
Copy by for
var b = [];
for(var i = len - 1; i >= 0 ; i--){
   b[i] = a[i];
}
pending…
Copy by for with init
var b = new Array(len);
for(var i = len - 1; i >= 0 ; i--){
   b[i] = a[i];
}
pending…
slice()
var b = a.slice();
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