4

Using JSON.parse(JSON.stringify(obj)) is an old trick i've seen used a lot for deep-copying objects. Does it create a truly 'deep-copy' of an object? Performance-wise, is it considered wise to use?

Eddie
  • 26,593
  • 6
  • 36
  • 58
nir segev
  • 338
  • 1
  • 4
  • 11
  • Not wise for performance in a lot of cases, and has the risk of throwing a stack overflow if the object has cyclical references. – Patrick Roberts Jan 29 '18 at 04:27
  • 1
    Possible duplicate of [What is the most efficient way to deep clone an object in JavaScript?](https://stackoverflow.com/questions/122102/what-is-the-most-efficient-way-to-deep-clone-an-object-in-javascript) – Patrick Roberts Jan 29 '18 at 04:30

2 Answers2

5

The biggest problem with using this method to deep-copy an object is the fact the object must be JSON serializable. For example, the following object:

let obj = {
    func: function() {
        console.log("hello world!");
    }
}

Would not be copied properly since functions are not JSON serializable. There are many other issues as well, such as with cyclic references. This really only works for simple, plain objects and thus isn't a particularly good solution. I would recommend checking out something like an underscore or a lodash for high-performance deep copying.

HoldOffHunger
  • 18,769
  • 10
  • 104
  • 133
treyhakanson
  • 4,611
  • 2
  • 16
  • 33
3

A few problems exist with the JSON.parse(JSON.stringify(obj))

The main issue for most developers is the loss of anything not part of the JSON spec

  • Any internal getters and setters will be lost.
  • Destruction of date objects (Dates will be converted to strings
  • Class prototypes will be lost.

The JSON method will also throw an exception when parsing circular references.

That said it does have some advantages for it:

  • Raw speed the JSON method wins out over even most shallow copy methods in benchmarks
  • Due to native implementation in the browser unlike a library it does not need to be shipped to the client, possibly also speeding up page load times.

As far as creating a truly deep copy of the object... it will be a truly deep copy as it will go as many levels into the object as it can, it won't be in that it will discard certain information, as outlined above.

HoldOffHunger
  • 18,769
  • 10
  • 104
  • 133
macdja38
  • 493
  • 3
  • 16