Cloning an Object

JavaScript performance comparison

Revision 13 of this test case created by Matteo Mirk

Info

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

discussion on StackOverflow

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.

Edit:

* added more value types to clone
* added internal and self references to the object to clone.
* added tests for major libs providing a clone() function

Preparation code

<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js">
</script>
<script src="http://documentcloud.github.com/underscore/underscore-min.js">
</script>
<script src="http://ajax.aspnetcdn.com/ajax/4.0/1/MicrosoftAjax.js">
</script>
<script src="http://yui.yahooapis.com/combo?3.5.0/build/yui-base/yui-base-min.js&3.5.0/build/oop/oop-min.js">
</script>
<script src="https://ajax.googleapis.com/ajax/libs/dojo/1.7.2/dojo/dojo.js">
</script>
<script src="http://cdn.sencha.io/ext-4.0.7-gpl/ext-all.js">
</script>
<script src="http://oranlooney.com/static/javascript/deepCopy.js"></script>

<script>
  var oldObject = {
    a: 1,
    b: "str",
    c: true,
    d: false,
    e: null,
    f: function() {
      return 6;
    },
    g: [7, 8, 9],
    h: new Date(),
    i: {
      a: new Date()
    },
    f: /asd/i,
    u: undefined
  };
  // references
  oldObject.ref = oldObject.g;
  oldObject.i.deep_ref = oldObject.f;
  // cyclic reference
  oldObject.self = oldObject;


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

  function clone2(o, b) {
    var a;
    if (Date.isInstanceOfType(o)) {
      return new Date((o).getTime());
    } else if (Array.isInstanceOfType(o)) {
      a = [];
    } else if (Function.isInstanceOfType(o)) {
      return o;
    } else if (Object.isInstanceOfType(o)) {
      a = {};
    } else {
      return o;
    }
    for (var i in o) {
      if (b || o.hasOwnProperty(i)) {
        a[i] = clone2(o[i]);
      }
    }
    return a;
  }

  function cloneJsonObject(o) {
    // similar to clone2, but assuming o came from a JSON string, so we can skip hasOwnProperty checks
    var a;
    if (Date.isInstanceOfType(o)) {
      return new Date((o).getTime());
    } else if (Array.isInstanceOfType(o)) {
      a = [];
    } else if (Function.isInstanceOfType(o)) {
      return o;
    } else if (Object.isInstanceOfType(o)) {
      a = {};
    } else {
      return o;
    }
    for (var i in o) {
      a[i] = cloneJsonObject(o[i]);
    }
    return a;
  }

  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
    }
  });

  //setup YUI module
  Y = YUI().use('oop');
</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…
simple clone function
var newObject = clone(oldObject);
pending…
ES5 Object.clone
var newObject = Object.clone(oldObject);
pending…
MSAjax
// This properly clones dates, but it is slow
var newObject = Sys.Serialization.JavaScriptSerializer.deserialize(Sys.Serialization.JavaScriptSerializer.serialize(oldObject));
pending…
Properly clone dates
// This properly clones dates and is faster than serializing
var newObject = clone2(oldObject, true);
pending…
cloneJsonObject
// Similar to the above, but assumes all properties in the object must be cloned, therefore skips the hasOwnProperty check.
var newObject = cloneJsonObject(oldObject);
pending…
undescore clone
var newObject = _.clone(oldObject)
pending…
YUI clone
var newObject = Y.clone(oldObject, true) // safe: no prototype cloning
pending…
Dojo clone
var newObject = dojo.clone(oldObject)
pending…
ExtJS 4 clone
var newObject = Ext.clone(oldObject)
pending…
OWL deep copy
var newObject = owl.deepCopy(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