array cloning

JavaScript performance comparison

Revision 25 of this test case created by dan

Info

Speed comparisons between slice, splice, concat

Discovering if array with data of the same type is cloned faster

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    var a = [1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0];
    var b1 = a.concat([1, 2]);
    var b2 = a.concat([{a: 1, b: 'a'}, {c: 'dsfase', d: {a: 1, x: 2}}]);
   
};

Benchmark.prototype.teardown = function() {
    if (c.length !== b1.length || c.length !== b2.length) {
      throw {message: "Test failed! b.length !== c.length"};
    }
   
    for (var i = 0, l = c.length; i < l; i++) {
    // we compare with || before l - 2 and with && afterwards
      if (i < l - 2)
        if (b1[i] !== c[i] || b2[i] !== c[i]) {
          throw {message: "Test failed! Arrays' content not equal on index  " + i};
        }
      else
        if (b1[i] !== c[i] && b2[i] !== c[i]) {
          throw {message: "Test failed! Arrays' content not equal on index  " + i};
        }
    }
   
    c[0].test = 'hi';
    if (b1[0].test === 'hi' || b2[0].test === 'hi') {
      throw {message: "Not a deep 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
slice, clean
c = b1.slice();
 
pending…
slice, dirty
c = b2.slice();
 
pending…
concat, clean
c = b1.concat();
 
pending…
concat, dirty
c = b2.concat();
 
pending…
while loop clean
//for (var i = 0, l = a.length; i < l; i++) {
//  c[i] = b1[i];
//}
var c = [];
var i = b1.length;
while(i--) { c[i] = b1[i]; }
 
pending…
while loop dirty
var c = [];
var i = b2.length;
while(i--) { c[i] = b2[i]; }
 
pending…
slice(0) clean
c = b1.slice(0);
 
pending…
slice(0) dirty
c = b2.slice(0);
 
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