cloning an object

JavaScript performance comparison

Revision 32 of this test case created by Nir

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.

Preparation code

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
 
<script>
Benchmark.prototype.setup = function() {
    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.");
      }
};
</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 stringify/parse
var newObject = JSON.parse(JSON.stringify(oldObject));
pending…
clone function
var newObject = clone(oldObject);
pending…
stringify eval
var newObject = eval("(" + JSON.stringify(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

Comment form temporarily disabled.

Add a comment