Cloning an Object

JavaScript performance comparison

Revision 24 of this test case created by check if all arrays are empty

Info

There is no quick and easy facility for cloning an object, Some people recommend using JQuery.extend others JSON.parse/stringify

http://stackoverflow.com/questions/122102/what-is-the-most-efficient-way-to-clone-a-javascript-object

If you want the fastest possible clone function. I would personally anticipate the data structure of your object and write a custom clone to handle it. (see Revision 3 by Corban Brook)

Revision 22: added LoDash since someone brought Underscore, using CDN for UnderScore

Preparation code

<script src="http://code.jquery.com/jquery-1.5.1.js" type="text/javascript"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.3.3/underscore-min.js"></script>
<script>var underscore = _.noConflict();</script>
<script src="https://raw.github.com/bestiejs/lodash/master/lodash.min.js"></script>
<script>var lodash = _.noConflict();</script>
<script>
  //allow UnderScore vs LoDash
  var lodash = window.lodash,
      underscore = window.underscore;

  //continue test setup
  var oldObject = {
    a: 1,
    b: 2,
    c: 3,
    d: 4,
    e: 5,
    f: function() {
      return 6;
    },
    g: [7, 8, 9]
  };


  function clone(obj) {
    var target = {};
    for (var i in obj) {
      if (obj.hasOwnProperty(i)) {
        target[i] = obj[i];
      }
    }
    return target;
  }

  function clone_deep(obj) {
    var target = {};
    for (var i in obj) {
      if (typeof(obj) === 'object') {
        target[i] = clone_deep(obj[i]);
      }
      else {
        target[i] = obj[i];
      }
    }
    return target;
  }

  Object.defineProperties(Object, {
    'extend': {
      'configurable': true,
      'enumerable': false,
      'value': function extend(what, wit) {
        var extObj, witKeys = Object.keys(wit);

        extObj = Object.keys(what).length ? Object.clone(what) : {};

        witKeys.forEach(function(key) {
          Object.defineProperty(extObj, key, Object.getOwnPropertyDescriptor(wit, key));
        });

        return extObj;
      },
      'writable': true
    },
    'clone': {
      'configurable': true,
      'enumerable': false,
      'value': function clone(obj) {
        return Object.extend({}, obj);
      },
      'writable': true
    }
  });


function struct_clone (oToBeCloned) {
  if (oToBeCloned === null || !(oToBeCloned instanceof Object)) { return oToBeCloned; }
  var oClone, fConstr = oToBeCloned.constructor;
  switch (fConstr) {
    // implement other special objects here!
    case RegExp:
      /*
      oClone = new fConstr(oToBeCloned.source, Array.prototype.filter.call("gim", function () {
        return (oToBeCloned.global | oToBeCloned.ignoreCase << 1 | oToBeCloned.multiline) & 1 << arguments[1];
      }).join(""));
      */

      oClone = new fConstr(oToBeCloned.source, "g".substr(0, Number(oToBeCloned.global)) + "i".substr(0, Number(oToBeCloned.ignoreCase)) + "m".substr(0, Number(oToBeCloned.multiline)));
      break;
    case Date:
      oClone = new fConstr(oToBeCloned.getTime());
      break;
    // etc.
    default:
      oClone = new fConstr();
  }
  for (var sProp in oToBeCloned) { oClone[sProp] = clone(oToBeCloned[sProp]); }
  return oClone;
}
</script>

Preparation code output

Test runner

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

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
JQuery.extend deep
var newObject = jQuery.extend(true, {}, oldObject);
pending…
JSON
var newObject = JSON.parse(JSON.stringify(oldObject));
pending…
JQuery.extend
var newObject = jQuery.extend({}, oldObject);
pending…
simple clone function
var newObject = clone(oldObject);
pending…
ES5 Object.clone
var newObject = Object.clone(oldObject);
pending…
slice(0)
var newObject = oldObject.slice(0);
pending…
underscore.clone
var newObject = underscore.clone(oldObject);
pending…
lodash.clone
var newObject = lodash.clone(oldObject);
pending…
clone_deep
var newObject = clone_deep(oldObject);
pending…
structured clone
var newObject = struct_clone(oldObject);
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