Skip to content

Instantly share code, notes, and snippets.

@valueof
Created July 18, 2013 23:34
Show Gist options
  • Save valueof/6033987 to your computer and use it in GitHub Desktop.
Save valueof/6033987 to your computer and use it in GitHub Desktop.
Which approach to cloning objects is faster? (Assuming there are no circular references, get/set, etc.)
// Candidate 1
JSON.parse(JSON.stringify(obj));
// Candidate 2
var desc = {};
Object.keys(obj).forEach(function(key) {
desc[key] = Object.getOwnPropertyDescriptor(obj, key);
});
Object.create(Object.prototype, desc);
@rauschma
Copy link

As @simevidas said: candidate 1 discards all non-JSON values.

For candidate 2, I’d use Object.getOwnPropertyNames() instead of Object.keys(). As @getify mentioned, you’ll have problems whenever a property contains a mutable value (such as an array). If you are working with your own objects, a different technique may be better. For example: a copy constructor, a constructor that initializes the current instance via another instance. Lastly, line 9 should be:

Object.create(Object.getPrototypeOf(obj), desc);

If you are after speed, the following variation of candidate 2 may be faster (maybe with a normal for loop instead of foreach):

var clone = Object.create(Object.getPrototypeOf(obj));
Object.getOwnPropertyNames(obj).forEach(function (key) {
    Object.defineProperty(clone, key, Object.getOwnPropertyDescriptor(obj, key));
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment