object cloning

JavaScript performance comparison

Test case created by Nikolay Frantsev

Preparation code

<script>
  var options = {
    "missing": {
      "enabled": true,
      "preview": 2,
      "hover": {
        "enabled": false,
        "timeout": 0.5
      },
      "global": true
    },
 
    "expert": {
      "enabled": true,
      "answers": {
        "preview": 2
      },
      "tips": {
        "preview": 3
      },
      "hover": {
        "enabled": true,
        "timeout": 0.5
      },
      "global": true
    },
 
    "auth": {
      "login": "",
      "password": "",
      "password_hash": ""
    },
 
    "urlinfo": {
      "age": true,
      "prevclick": true
    },
 
    "survey": {
      "enabled": true
    }
  }
</script>

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
eval/uneval
function cloneObject(obj) {
  return eval(uneval(obj));
}

var clone = cloneObject(options);
pending…
json parse/stringify
function cloneObject(obj) {
  return JSON.parse(JSON.stringify(obj));
}

var clone = cloneObject(options);
pending…
cloning properties
function cloneObject(obj) {
  var clone = {};

  for (var i in obj)
  if (typeof obj[i] == "object") clone[i] = cloneObject(obj[i]);
  else clone[i] = obj[i];

  return clone;
}

var clone = cloneObject(options);
pending…
cloning prototype
function cloneObject(obj) {
  function clone() {}
  clone.prototype = obj;
  return new clone();
}

var clone = cloneObject(options);
pending…
object.create
function cloneObject(obj) {
  return Object.create(obj);
}

var clone = cloneObject(options);
pending…
fastest cross-browser way
function cloneObject(obj) {
  if ("create" in Object) return Object.create(obj);

  function clone() {}
  clone.prototype = obj;
  return new clone();
}

var clone = cloneObject(options);
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

Add a comment