clone objects (v2)

Revision 2 of this benchmark created by Kyle Simpson on


Preparation HTML

<script>
function clone(obj) {
  var copy, i, len;
    // Handle the 3 simple types, and null or undefined
    if (null == obj || "object" != typeof obj) return obj;

    // Handle Date
    if (obj instanceof Date) {
        copy = new Date();
        copy.setTime(obj.getTime());
        return copy;
    }

    // Handle Array
    if (obj instanceof Array) {
        copy = [];
        for (i = 0, len = obj.length; i < len; ++i) {
            copy[i] = clone(obj[i]);
        }
        return copy;
    }

    // Handle Object
    if (obj instanceof Object) {
        copy = {};
        for (attr in obj) {
            if (obj.hasOwnProperty(attr)) copy[attr] = clone(obj[attr]);
        }
        return copy;
    }

    throw new Error("Unable to copy obj! Its type isn't supported.");
};


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] = struct_clone(oToBeCloned[sProp]); }
  return oClone;
};


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

Test runner

Ready to run.

Testing in
TestOps/sec
clone
var newObject = clone(oldObject);
ready
structured clone
var newObject = struct_clone(oldObject);
ready
json
var newObject = JSON.parse(JSON.stringify(oldObject));
ready

Revisions

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

  • Revision 2: published by Kyle Simpson on