Created
July 18, 2013 23:34
-
-
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.)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
As @simevidas said: candidate 1 discards all non-JSON values.
For candidate 2, I’d use
Object.getOwnPropertyNames()
instead ofObject.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:If you are after speed, the following variation of candidate 2 may be faster (maybe with a normal
for
loop instead offoreach
):