Cloning an Object (v56)

Revision 56 of this benchmark created on


Description

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.

Preparation HTML

<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
</script>
<script>
  var oldObject = {
    a: 1,
    b: 2,
    c: 3,
    d: 4,
    e: 5,
    f: function() {
      return 6;
    },
    g: {
      a: [7, 8, 9, 5, 545, 456, 456, 56, 345, 345, 354, 5, 345, 345, 345, 524, 2, 35, 64, 456, 76, 675, 757, 573, 6, 456, 364, 646, 456, 463, 6352, 247, 768, 85, 74, 352, 576, 78789, 79],
      b: [123, 345, 6745, 34546, 635, 24, 235, 76, 515, 67, 572, 5315, 756, 7, 789, 3, 632, 5, 4578, 53623, 6357, 346, 6, 657, 76867, 74, 6, 65, 80, 89],
      c: [676745.5, 6756, 4, 64, 767, 678678, 34534, 535, 456, 5367, 5667, 85, 756, 758, 68, 547, 8, 85, 7654, 767, 8, 877, 8, 87367, 3, 65, 6, 6, 2, 52, 43, 25, 2, 5, 76678, 89]
    }
  };


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

  function deepclone(obj) {
    var target = {};
    for (var i in obj) {
      if (obj.hasOwnProperty(i)) {
        target[i] = typeof obj[i] == 'object' ? deepclone(obj[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
    }
  });
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
JQuery.extend deep
var newObject = jQuery.extend(true, {}, oldObject);
ready
JSON
var newObject = JSON.parse(JSON.stringify(oldObject));
ready
JQuery.extend
var newObject = jQuery.extend({}, oldObject);
ready
simple clone function
var newObject = clone(oldObject);
ready
simple deep clone function
var newObject = deepclone(oldObject);
ready

Revisions

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