cloning an object

JavaScript performance comparison

Revision 32 of this test case created by Nir


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

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=""></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();
          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.");

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);
JSON stringify/parse
var newObject = JSON.parse(JSON.stringify(oldObject));
clone function
var newObject = clone(oldObject);
stringify eval
var newObject = eval("(" + JSON.stringify(oldObject) + ")");

Compare results of other browsers


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:


Comment form temporarily disabled.

Add a comment