Deep copy object (jQuery vs other)

Benchmark created by peol on


Description

Deep copy/extend objects, jQuery versus other approach(es)

Preparation HTML

<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
 
<script>
 /*!
  * Copyright Andrée Hansson, 2010
  * Use it however you want, attribution would be nice though.
  *
  * GMail/Twitter:  peolanha
  * IRC (FreeNode): peol
  * Website:        http://andreehansson.se/
  */
 
 !
 function() {
  window.deepCopyObject = function(extendee, extender) {
   for (var o in extender) {
    extendee[o] = getValue(extender[o]);
   }
 
   return extendee;
  }
 
  function getValue(obj) {
   var
   isArray = obj.constructor.toString().indexOf('Array') >= 0,
       isObject = obj.constructor.toString().indexOf('Object') >= 0,
       val, i = 0,
       l;
 
   // Object
   if (isObject) {
    val = deepCopyObject(obj);
   }
 
   // Array
   else if (isArray) {
    val = Array.apply(null, obj);
    do {
     val[i] = getValue(val[i]);
    }
    while (i++ < l);
   }
 
   // Others
   else {
    val = obj;
   }
 
   return val;
  }
 }();
 
 // Testing
 !
 function() {
  var
  a = {
   a: '1',
   b: {
    a: '1',
    b: [{
     a: '1'}]
   }
  },
      b = deepCopyObject({
    'hello': 'world'
   }, a);
  b.a = '2';
  b.b.a = '2';
  b.b.b[0].a = '2';
  console.log(a, b);
 }();
 
 var a = {
  a: '1',
  b: {
   a: '1',
   b: [
    {
    a: '1'},
   {
    b: '1'},
   {
    c: '1'},
   {
    d: '1'}
   ]
  }
 };
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
jQuery
$.extend(true, {
 c: '1'
}, a);
ready
Other
deepCopyObject({
 c: '1'
}, a);
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.