2

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);
        }
    }
JasonMArcher
  • 14,195
  • 22
  • 56
  • 52
Dmitry Makovetskiyd
  • 6,942
  • 32
  • 100
  • 160

1 Answers1

0

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

Console.WriteLine("Serialized size "+ms.Position);

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.

Anders Forsgren
  • 10,827
  • 4
  • 40
  • 77
  • it is 0 each time..but..it is being called 8 -10 times in a row.. the message pops up 8 times in a row when i click a button (which calls the function) – Dmitry Makovetskiyd Aug 19 '11 at 08:49
  • The position is zero every time? Are you sure you added the console.writeline after the call to serialize and before you set the position to zero? If you se more calls than you expect, I think you probably add the handler more than once to to your control! I.e. check where you do += and handle the button click. Don't add a handler more than once! – Anders Forsgren Aug 19 '11 at 08:53
  • it is 1607..each time.being called about 20 times – Dmitry Makovetskiyd Aug 19 '11 at 11:23
  • I think your problem is not with serialization then but with the handler being invoked many times. Set a breakpoint on the line where you add the click handler i.e. in button1.Clicked += new EventHandler(MyHandlerMethod); You should only break att that breakpoint once. Otherwise, fix that problem so you only add the handler once. – Anders Forsgren Aug 19 '11 at 12:02
  • those are the loops, in my code... I think i found the problem..it isnt the deep cloning – Dmitry Makovetskiyd Aug 19 '11 at 13:45