c# – Deep cloning objects – Stack Overflow

Q. Why would I choose this answer?

In other words, go with another answer unless you have a performance bottleneck that needs fixing, and you can prove it with a profiler.

The following method of performing a deep clone is:

For ultimate speed, you can use Nested MemberwiseClone to do a deep copy. Its almost the same speed as copying a value struct, and is much faster than (a) reflection or (b) serialization (as described in other answers on this page).

Note that if you use Nested MemberwiseClone for a deep copy, you have to manually implement a ShallowCopy for each nested level in the class, and a DeepCopy which calls all said ShallowCopy methods to create a complete clone. This is simple: only a few lines in total, see the demo code below.

Here is the output of the code showing the relative performance difference for 100,000 clones:

Using Nested MemberwiseClone on a class almost as fast as copying a struct, and copying a struct is pretty darn close to the theoretical maximum speed .NET is capable of.

To understand how to do a deep copy using MemberwiseCopy, here is the demo project that was used to generate the times above:

Then, call the demo from main:

Again, note that if you use Nested MemberwiseClone for a deep copy, you have to manually implement a ShallowCopy for each nested level in the class, and a DeepCopy which calls all said ShallowCopy methods to create a complete clone. This is simple: only a few lines in total, see the demo code above.

Note that when it comes to cloning an object, there is is a big difference between a "struct" and a "class":

See differences between value types and references types.

One excellent use case for this code is feeding clones of a nested class or struct into a queue, to implement the producer / consumer pattern.

This works extremely well in practice, and allows us to decouple many threads (the producers) from one or more threads (the consumers).

And this method is blindingly fast too: if we use nested structs, it's 35x faster than serializing/deserializing nested classes, and allows us to take advantage of all of the threads available on the machine.

Apparently, ExpressMapper is as fast, if not faster, than hand coding such as above. I might have to see how they compare with a profiler.

Continue reading here:

c# - Deep cloning objects - Stack Overflow

Related Posts

Comments are closed.