Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
228 views
Welcome To Ask or Share your Answers For Others

1 Answer

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/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...