cloning an object

JavaScript performance comparison

Revision 3 of this test case created

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="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>

<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
 
<script>
Benchmark.prototype.setup = function() {
    var oldObject = {
       a: 1,
       b: 2,
       c: 3,
       d: 4,
       e: 5,
       f: 'Yet for all that, the learned know that certain worthy men have been brought to untimely death for none other fault, but for seeking to reduce their countrymen to good order and discipline; and that in some commonweals it was made a capital crime, once to motion the making of a new law for the abrogating of an old, though the same were most pernicious; and that certain, which would be counted pillars of the state, and patterns of virtue and prudence, could not be brought for a long time to give way to good letters and refined speech, but bare themselves as averse from them, as from rocks or boxes of poison; and fourthly, that he was no babe, but a great clerk, that gave forth (and in writing to remain to posterity) in passion peradventure, but yet he gave forth, that he had not seen any profit to come by any synod, or meeting of the clergy, but rather the contrary; and lastly, against church maintenance and allowance, in such sort, as the ambassadors and messengers of the great King of Kings should be furnished, it is not unknown what a fiction or fable (so it is esteemed, and for no better by the reporter himself, though superstitious) was devised--namely, that at such a time as the professors and teachers of Christianity in the Church of Rome, then a true church, were liberally endowed, a voice forsooth was heard from heaven, saying, "Now is poison poured down into the church," etc.. Thus not only as oft as we speak, as one saith, but also as oft as we do anything of note or consequence, we subject ourselves to everyone\'s censure, and happy is he that is least tossed upon tongues; for utterly to escape the snatch of them it is impossible. If any man conceit, that this is the lot and portion of the meaner sort only, and that princes are privileged by their high estate, he is deceived. "As the sword devoureth as well one as the other," as it is in Samuel ; nay, as the great commander charged his soldiers in a certain battle, to strike at no part of the enemy, but at the face; and as the king of Syria commanded his chief captains to "fight neither with small nor great, save only against the king of Israel" ; so it is too true, that Envy striketh most spitefully at the fairest, and at the chiefest. David was a worthy prince, and no man to be compared to him for his first deeds, and yet for as worthy as act as ever he did (even for bringing back the Ark of God in solemnity), he was scorned and scoffed at by his own wife. Solomon was greater than David--though not in virtue, yet in power--and by his power and wisdom he built a temple to the LORD, such a one as was the glory of the land of Israel, and the wonder of the whole world. But was that his magnificence liked of by all? We doubt of it. Otherwise, why do they lay it in his son\'s dish, and call unto him for easing of the burden : "Make," say they, "the grievous servitude of thy father, and his sore yoke, lighter"? Belike he had charged them with some levies, and troubled them with some carriages. Hereupon they raise up a tragedy, and wish in their heart the temple had never been built. So hard a thing it is to please all, even when we please God best, and do seek to approve ourselves to every one\'s conscience.',
       g: [7, 8, 9]
      };
     
     
      function clone(obj) {
       var target = {};
       for (var i in obj) {
        if (obj.hasOwnProperty(i)) {
         target[i] = obj[i];
        }
       }
       return target;
      }
     
      Object.defineProperties(Object, {
       'extend': {
        'configurable': true,
        'enumerable': false,
        'value': function extend(what, wit) {
         var extObj, witKeys = Object.keys(wit);
     
         extObj = Object.keys(what).length ? Object.clone(what) : {};
     
         witKeys.forEach(function(key) {
          Object.defineProperty(extObj, key, Object.getOwnPropertyDescriptor(wit, key));
         });
     
         return extObj;
        },
        'writable': true
       },
       'clone': {
        'configurable': true,
        'enumerable': false,
        'value': function clone(obj) {
         return Object.extend({}, obj);
        },
        'writable': true
       }
      });
};
</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…
jQuery.extend()
var newObject = jQuery.extend({}, oldObject);
pending…
clone function
var newObject = clone(oldObject);
pending…
ES5 Object.clone
var newObject = Object.clone(oldObject);
pending…
stringify eval
var newObject = eval("("+JSON.stringify(oldObject)+")");
pending…
angular copy
var newObject = angular.copy(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

Add a comment