I want to create deep copy method and I found 3 ways to execute it
1-deep copy with pass each property 1 by 1
2-using reflection
3-using serialization
please which of them is the best at performance wise
1. In Shallow copy, a copy of the original object is stored and only the reference address is finally copied. In Deep copy, the copy of the original object and the repetitive copies both are stored.
According to the benchmark test, the fastest way to deep clone an object in javascript is to use lodash deep clone function since Object. assign supports only shallow copy.
clone() is indeed a shallow copy. However, it's designed to throw a CloneNotSupportedException unless your object implements Cloneable . And when you implement Cloneable , you should override clone() to make it do a deep copy, by calling clone() on all fields that are themselves cloneable.
A deep copy of an object is a copy whose properties do not share the same references (point to the same underlying values) as those of the source object from which the copy was made.
The first option, manually deep copying your values, will be the most performant by far.
Reflection will introduce quite a bit of overhead, as it is (relatively) slow to access data.
Serialization is adding a huge cost, as it serializes the data into a temporary structure, then reverses the process to set. This is again, very slow.
The only advantage to option 2 or 3 is that its potentially easier to implement, and reusable across multiple types. The first option has to be hand-written per type, but is much faster (and more efficient in memory usage than option 3, as well).
I made graph with comparison of the three methods plus an expression trees method.
For large number of objects is reflection 5x faster and manual code and expression trees are 20x faster than serialization. The best by performance are therefore manual code and expression trees.
Links to used cloning codes (2.-4. used as an extension method):
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With