Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Faster deep cloning

Tags:

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.

like image 865
Karol Kolenda Avatar asked May 12 '09 10:05

Karol Kolenda


People also ask

How can you achieve the deep cloning of an object?

To achieve a deep copy, we can serialize an object and then deserialize it to a new object.

What is the most efficient way to deep clone an object in javascript?

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.

What is the difference between a shallow copy and a deep 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.

Does object assign do a deep copy?

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.


1 Answers

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.

Logarithmic scale illustrating cloning performance

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/

like image 118
Cygon Avatar answered Nov 15 '22 00:11

Cygon