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: