Karol Kolenda Karol Kolenda - 1 year ago 101
C# Question

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

(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.

Many thanks,

Answer Source

If you are talking about an object tree/graph:

Writing specific IL to serialize an object is tricky. IMO, your best bet is to look at a full serialization, like how DataContractSerializer would work - but not necessarily with that engine.

For example, protobuf-net has a Serializer.DeepClone<T> method that might help. It should be faster than DataContractSerializer, at least. At the current time, you need to add some clues for the serializer (even if just [ProtoContract(ImplicitFields=ImplicitFields.AllPublic)]) - however, the current (incomplete) work-in-progress offers POCO support without attributes.

If you are talking about individual objects:

There are fairly simple things you can do here with Expression in .NET 3.5; build a dynamic Expression based on reflection, and call .Compile(). MiscUtil has this already:

DestType clone = PropertyCopy<DestType>.CopyFrom(original);

With .NET 2.0/3.0 (without Expression) you might consider HyperDescriptor for similar purposes.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download