I have a collection of objects and I am trying to clone this collection and trying to understand performance implication of different approaches.
The object in the collection has about 20 properties all strings, ints, floats (this objects doesn’t have any nested objects inside of it). The two approaches are:
-
Create DeepClone() method:
public static class ExtensionMethods { public static T DeepClone<T>(this T a) { using (var stream = new MemoryStream()) { var formatter = new BinaryFormatter(); formatter.Serialize(stream, a); stream.Position = 0; return (T)formatter.Deserialize(stream); } }}
-
Manually write “copy” code where i am looping through the collection and “new”ing a new object and then manually setting all of the 20 properties. something like this
public MyObject Copy(MyObject myObj) { var obj = new MyObject(); obj.Prop1 = myObj.Prop1; obj.Prop2 = myObj.Prop2; return obj;}
I am getting very inconsistent results so I wanted to get peoples feedback on:
-
Should one be much faster that the other? I would have thought choice two but my tests don’t seem to support this so I am trying to figure out if I am doing something wrong.
-
Is there any way to do this even faster?
Well, first of all BinaryFormatter route must definitely be slower, since it uses reflection to get/set properties. The most common method is using the IClonable interface in conjunction with a copy constructor.
Of course strictly speaking you only need the copy constructor, which should be the fastest method. If your objects are simple, you should try using in-built MemberwiseClone function.
Meanwhile, I wrote some test code to see if MemberwiseClone() was severely faster or slower than using a copy constructor. You can find it here. I found that MemberwiseClone is actually much slower than doing a CopyConstructor, at least on small classes. Note that using the BinaryFormatter is insanely slow.