I believe that the BinaryFormatter approach is relatively slow (which came as a surprise to me!). You might be able to use ProtoBuf .NET for some objects if they meet the requirements of ProtoBuf. From the ProtoBuf Getting Started page (http://code.google.com/p/protobuf-net/wiki/GettingStarted):
Notes on types supported:
Custom classes that:
- Are marked as data-contract
- Have a parameterless constructor
- For Silverlight: are public
- Many common primitives, etc.
- Single dimension arrays: T[]
- List / IList
- Dictionary / IDictionary
- any type which implements IEnumerable and has an Add(T) method
The code assumes that types will be mutable around the elected members. Accordingly, custom structs are not supported, since they should be immutable.
If your class meets these requirements you could try:
public static void deepCopy(ref T object2Copy, ref T objectCopy)
{
using (var stream = new MemoryStream())
{
Serializer.Serialize(stream, object2Copy);
stream.Position = 0;
objectCopy = Serializer.Deserialize(stream);
}
}
Which is VERY fast indeed...
Edit:
Here is working code for a modification of this (tested on .NET 4.6). It uses System.Xml.Serialization and System.IO. No need to mark classes as serializable.
public void DeepCopy(ref T object2Copy, ref T objectCopy)
{
using (var stream = new MemoryStream())
{
var serializer = new XS.XmlSerializer(typeof(T));
serializer.Serialize(stream, object2Copy);
stream.Position = 0;
objectCopy = (T)serializer.Deserialize(stream);
}
}