Deep Clone Test

JavaScript performance comparison

Revision 3 of this test case created by Glutamat

Preparation code


      
      <script>
Benchmark.prototype.setup = function() {
  Object.prototype.getType = function() { //Adds a method to the Objects Prototype
  	return Object.prototype.toString.call(this).match(/^\[object (.+?)\]$/)[1]; //Calls the Objects toString method with the OBject which has called the method, and matches the output tot return the type
  };
  Object.defineProperty(Object.prototype, "getType", { //sets the enumerable descriptor of the getType method to fals ->  the method doesn't show up when iterating over an Objects Property 
  	enumerable : false
  });
  Object.prototype.clone = function(deep, falseAray) { //Deep clones an Object
  	/*Syntax:
  	 * e.g:
  	 *var test = {}
  	 * var test2 = test.clone(true) //deep clones to an unlimited level
  	 * var test3 = test.clone(2) // to level 2
  	 */
  	if (this.getType() !== "Object") {
  		return this.valueOf;
  	}
  	/*var falseArray;
  	if(check) {
  	falseArray = (Object.keys(this).length - this.length);
  	}*/ //takes around 400ms additional at 500k array to check if it has additional properties, just pass it as argument
  	var clone = {};
  	if (!deep) {
  		for (var prop in this) {
  			clone[prop] = this[prop];
  		}
  	} else {
  		for (var prop in this) {
  			if ( typeof this[prop] !== "undefined" && this[prop] !== null)
  				clone[prop] = ( typeof this[prop] !== "object" ? this[prop] : this[prop].clone(( typeof deep == "boolean" ? deep : (deep - 1))));
  			else
  				clone[prop] = "";
  		}
  	}
  	return clone;
  };
  Object.defineProperty(Object.prototype, "clone", {
  	enumerable : false
  });
  
  
      var toClone = {};
      
      for ( var i = 0; i < 500 ; i++ ) {
      toClone[i] = {};
         for (var j = 0; j < 500; j++) {
      toClone["Asd"+i] = "fgh" + i;
      toClone[i][j] = {};
           for (var k = 0 ; k < 5 ; k++) {
      toClone[i]["ASD" + j] = "ASDF" + j;
      toClone[i][j][k] = "ASDF";
      }}}
  

};
</script>

Test runner

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

Java applet disabled.

Testing in CCBot 2.0.0 / Other 0.0.0
Test Ops/sec
Clone()
var t = toClone.clone(true)
pending…
JSON
var t = JSON.parse(JSON.stringify(toClone));
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.

0 Comments