cloning an object (v32)

Revision 32 of this benchmark created by Nir 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>

Setup

var oldObject = {
      date: new Date(),
      func: function(q) {
        return 1 + q;
      },
      num: 123,
      text: "asdasd",
      array: [1, "asd"],
      regex: new RegExp(/aaa/i),
      subobj: {
        num: 234,
        text: "asdsaD"
      }
    }
    
    
      function clone(obj) {
        var copy;
    
        // 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 (var i = 0, len = obj.length; i < len; i++) {
            copy[i] = clone(obj[i]);
          }
          return copy;
        }
    
        // Handle Object
        if (obj instanceof Object) {
          copy = {};
          for (var 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.");
      }

Test runner

Ready to run.

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

Revisions

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