I am using MemoryStream as deep cloning in one of my methods. I call that method a few times, and I notice the more I call it the more it slows my program. Is there a way to clear the memory stream each time, when I stop using the memory stream?
public static T DeepClone<T>(T obj)
{
using (var ms = new MemoryStream())
{
var formatter = new BinaryFormatter();
formatter.Serialize(ms, obj);
ms.Position = 0;
return (T)formatter.Deserialize(ms);
}
}
The memorystream is Disposed at the end of the using statement every call. It may not be garbage collected until later however. I don’t think that potential memory use is your problem though. If you get noticable speed differences between calls, I think you must be serializing a more complicated object each time. If you ad a diagnostic statment such as
after your call to
Serialize(), will it report the same number every time, or increasing size? If the size increases, then you are serializing a larger object graph each time, and the slowdown is expected.