2

we use the following code to deep copy an Element obj, the code will be executed thousands of times(copy thousands of different Elements), it takes us a lot of time(about 1 minute )

public static Element Clone(Element me)
    {
        MemoryStream stream = new MemoryStream();
        try
        {
            BinaryFormatter formatter = new BinaryFormatter();
            formatter.Serialize(stream, me);
            stream.Seek(0, SeekOrigin.Begin);

            return (Element)formatter.Deserialize(stream);
        }
        finally
        {
            stream.Close();
        }
    }

How can we improve the performance ?

liuzhidong
  • 538
  • 3
  • 18

1 Answers1

2

For the best performance, actually implement the Clone method for each class. Of course, that makes the maintenance cost higher -- on the other hand, it removes a part of the magic that happens, a lot of developers will feel more comfortable with an actual list of assignments.

Another approach is to implement your own cloning magic using System.Reflection to identify members to clone and Reflection.Emit to generate specific IL for each class.

While I would go for the second option personally, it does introduce a complexity of its own and as such will feel like magic again to some. I have successfully implemented a similar solution to clone objects trees whose types I could not alter myself (and were not serializable)

adt
  • 4,320
  • 5
  • 35
  • 54
TiMoch
  • 1,008
  • 1
  • 10
  • 17