none
Performance: MemoryStream and multi-thread access RRS feed

  • Question

  • Hi all,

    Here is the context:

    I send Message objects over the network. I use a MemoryStream to put the objects in bytes and then they are ready to go.

    Right now, the code looks like this:

    public byte[] GetBytes()<br/>
        {<br/>
          MemoryStream ms = new MemoryStream(); //we create a new object every time<br/>
          //otherwise we could have a shared object,<br/>
          //but we'd have to have a lock on it because several threads serialize/deserialize at the same time<br/>
          bf.Serialize(ms, this);<br/>
          byte[] data = ms.GetBuffer();<br/>
          return data;<br/>
        }
    

    This is inside the Message class.

     

    So everytime I want to send a message, I create a new MemoryStream object.

    I would like to use only one instance of it, but my application has many threads sending messages at the same time. Having a single MemoryStream would oblige me to take care of concurrent access...

     

    What solution offers the best performance?

    Is there another way of doing this ?

    Am I just too picky?

     

    Thank you

     

     

     

    Tuesday, July 20, 2010 4:16 PM

Answers

  • If you are really worried about this (especially could be a concern if the length in bytes exceeds the large object threshold of 85KB), you can create a pool of MemoryStream objects.  This pool will need to be thread-safe (using locks, etc.).  You will need a mechanism to release a MemoryStream back to the pool when your caller is done with it.  You will basically need to trust your callers to deal with the release properly.  I would zero out the buffer when the MemoryStream is placed back in the pool.

    All this said, I would not worry about doing this optimization unless you have identified it as a real performance issue in the context of your entire application.

     

    • Marked as answer by Joey252 Wednesday, July 21, 2010 1:26 PM
    Wednesday, July 21, 2010 12:10 AM

All replies

  • If you are really worried about this (especially could be a concern if the length in bytes exceeds the large object threshold of 85KB), you can create a pool of MemoryStream objects.  This pool will need to be thread-safe (using locks, etc.).  You will need a mechanism to release a MemoryStream back to the pool when your caller is done with it.  You will basically need to trust your callers to deal with the release properly.  I would zero out the buffer when the MemoryStream is placed back in the pool.

    All this said, I would not worry about doing this optimization unless you have identified it as a real performance issue in the context of your entire application.

     

    • Marked as answer by Joey252 Wednesday, July 21, 2010 1:26 PM
    Wednesday, July 21, 2010 12:10 AM
  • Thank you
    Wednesday, July 21, 2010 1:26 PM