tags:

views:

203

answers:

2

Anyone knows if there is an easy or known way to write a deep copy method that's gonna work on arrays of any kind, ie jagged, multidimensional, etc? I plan to write it as an extension method.

There isn't a default method in the framework to do this, right? I am surprised not to find one.

I have seen some serialization-based implementation and they were slow as hell, so I would like a solution which does not use any type of serialization.

+4  A: 

The current status of this question is a bit unclear; it was possibly a duplicate (noted in a deleted reply), but the comments suggest that this isn't quite suitable.

Re serialization slowing things down - well, unfortunately, there is no properly supported "deep clone" functionality in .NET. There is ICloneable, but that is a: rarely used, and b: not stated as either shallow or deep. As such, the only remaining reliable way to deep clone data is to use serialization.

Re "slow as hell", can you quantify that? Which serialization mechanism was that using? (BinaryFormatter? XmlSerializer?). For info, you might be interested in protobuf-net, which is a pretty fast and efficient alternative binary serializer (and which offers a very handy T DeepClone<T>(T) method) - however, it only works with classes that are marked in specific ways (for example, it can use either [DataContract] markers, or the bespoke [ProtoContract] markers). It is quicker than the inbuilt serializers, though.

The only other viable option is to write you own, per-type, deep copy routine, and perhaps pass that in (as a Func<T,T> or Converter<T,T> delegate) to your extension method.

If you only want a shallow copy, things are easier, as you can use reflection etc. Here's an option that creates a shallow copy using a compiled Expression (.NET 3.5) for improved performance.

Marc Gravell
Thanks Marc. The one I have used was this [one][1]. But it was very slow, it's used in a renderer, so the whole process slowed down by 3-4 times.Do you know if the .NET team is gonna implement a special method for this? [1]: http://www.developerfusion.com/code/8063/deep-clone-an-object-in-net/
Joan Venge
Btw how you add links to comments properly?
Joan Venge
A: 

I would first take a shot at this:

internal static class Prototype
{
  public static T DeepCopy<T>(this IPrototype<T> target)
  {
    T copy;
    using (var stream = new MemoryStream())
    {
      var formatter = new BinaryFormatter();
      formatter.Serialize(stream, (T)target);
      stream.Seek(0, SeekOrigin.Begin);
      copy = (T) formatter.Deserialize(stream);
      stream.Close();
    }
    return copy;
  }
}

If this isn't as fast as you want, then I'd optimize.

Dmitri Nesteruk
Yes, this is the code I used from the link I posted to Marc as a comment. It's very slow for my purposes. I need a reliable fast way to do it, but I guess I am doomed since .NET team didn't provide a special method.
Joan Venge