Deep Copy vs JSON Stringify / JSON Parse

JavaScript performance comparison

Revision 100 of this test case created by Jonathan Perry

Preparation code


      
      <script>
Benchmark.prototype.setup = function() {
    function deepCopy(o) {
        var copy = o,k;
     
        if (o && typeof o === 'object') {
            copy = Object.prototype.toString.call(o) === '[object Array]' ? [] : {};
            for (k in o) {
                copy[k] = deepCopy(o[k]);
            }
        }
     
        return copy;
    }
  
  function deepCopyFor(v) {
      if (Array.isArray(v)) {
          let i = 0;
          const n = v.length;
          const r = [];
          for (i, n; i < n; i = i + 1) {
              const c = v[i];
              r.push(deepCopyFor(c));
          }
          return r;  
      } 
  
      if ((v || false) instanceof Object) {
          const r = {};
          for (k in v) {
              const c = v[k];
              r[k] = deepCopyFor(c);
          }
          return r;    
      }
  
      return v;
  }
  
  var uc = {
      bir: {
        iki: {
          uc: 3,
          ab: null,
          f: {
            a: [1, 23, 67, 35, 24, 89, 12, 48674],
            ty: [{ a: 123, b: 34 }],
            l1: {
              l2: {
                l3: {
                  l4: 1234,
                },
              },
            },
          },
        },
      },
    };

};
</script>

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in CCBot 2.0.0 / Other 0.0.0
Test Ops/sec
Deep Copy For
var bes = deepCopyFor(uc)
pending…
Deep Copy
var bes = deepCopy(uc)
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.

0 Comments