Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
239 views
in Technique[技术] by (71.8m points)

c# - Faster deep cloning

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

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

1 Reply

0 votes
by (71.8m points)

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/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...