DeepCopy for arrays

Does anyone know if there is a simple or known way to write a deep copy method that will work on arrays of any type, i.e. serrated, multidimensional, etc.? I am planning to write it as an extension method.

There is no default method in the structure, right? I'm surprised I didn't find it.

I've seen some serialized implementation and they were slow as hell, so I would like to get a solution that doesn't use any kind of serialization.

+1


source to share


2 answers


The current state of this issue is a bit unclear; it may have been a duplicate (noted in the deleted answer), but the comments suggest it doesn't quite fit.

Re-serialization slows things down - well, unfortunately .NET doesn't have a properly supported "deep clone" feature. There is ICloneable

, but it is: rarely used, and b: not listed as shallow or deep. Thus, the only remaining reliable way to deeply clone data is to use serialization.

Re "slow as hell", can you quantify that? What was the serialization mechanism? ( BinaryFormatter

? XmlSerializer

?). For your information, you may be interested in protobuf-net , which is a fairly fast and efficient alternative binary serializer (and which offers a very convenient one T DeepClone<T>(T)

), however, it only works with classes marked in a certain way (for example, it can use markers [DataContract]

or [ProtoContract]

custom markers ) ... Still faster than built-in serializers.



The only other viable option is to write your own, for each type, deep copy procedure, and possibly pass that to (as a delegate Func<T,T>

or Converter<T,T>

) your extension method.

If you only want a shallow copy, things will be easier since you can use reflection, etc. Here option creates a small copy using a compiled one Expression

(.NET 3.5) for better performance.

+5


source


I would take a picture first:

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 it's not as fast as you want, I would optimize.

-1


source







All Articles