Does anyone want a framework/class which allows me to clone by values .Net objects? I'm only interested with public read/write properties (namely DataContracts), and I don't care if references are resolved correctly (i.e. collecions which contains the same instance of item twice).
I tried serialization trick via DataContractSerializer
(serialize to XML and back), wrote reflection-based cloning class (sometimes faster/sometimes slower), and was wondering if someone wrote a helper class which can do this via Emit and not reflection. As for now emitting IL is a little to much for my little brain, but I guess this would be the ultimate solution. Unless someone knows an alternative method which is faster than DataContractSerializer.
To achieve a deep copy, we can serialize an object and then deserialize it to a new object.
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.
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.
assign() was the most popular way to deep copy an object. Object. assign() will copy everything into the new object, including any functions. Mutating the copied object also doesn't affect the original object.
I have written three deep clone methods for .NET some time ago:
One uses the well-known BinaryFormatter
technique (though I tweaked it so that objects do not need to be serializable in order to be cloned). This was by far the slowest.
For the second I used pure reflection. It was at least 6 times faster than cloning with the BinaryFormatter
. This one could also be used on Silverlight and the .NET Compact Framework.
The third one uses Linq Expression Trees (for runtime MSIL generation). It is 60 times faster than the BinaryFormatter
technique but has a setup time of approximately 2 milliseconds for the first time each class is encountered.
The horizontal axis shows the number of objects cloned (though each cloned object includes several nested objects).
The BinaryFormatter
is labeled "Serialization" in the chart. The data series "Reflection" is a custom one that copies fields via GetField()
/SetField()
.
I published all three cloning methods as Open Source here:
http://blog.nuclex-games.com/mono-dotnet/fast-deep-cloning/
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