C#/.NET: UnmanagedMemoryStream for networking? – Education Career Blog

I was considering using UnmanagedMemoryStream rather than MemoryStream for dealing with incoming (and perhaps outgoing?) packets in a network server. What I hope to achieve is less copying of values, and if possible, avoid copying to the heap (too much).

For example, for an incoming packet, one could do:

fixed (byte* p = &data) // where data comes from a socket receive
{
    using (var stream = new UnmanagedMemoryStream(p, data.Length))
    {
        // do handling here...
    }
}

Still, I’m not quite sure if there is any realistic benefit in doing this. Could anyone come with some feedback as to whether or not there would be any value in doing this, rather than using the good old managed MemoryStream?

Thanks in advance.

,

This sounds like premature optimization to me. Have you used MemoryStream and done some profiling to show that it caused you tangible, measurable performance problems?

I would stick with the conventional MemoryStream and save myself the headache until it became obvious (through profiling) that it was necessary to change.

,

Nope, you didn’t improve what is already there. A byte is a reference type. You can simply pass it to the MemoryStream(byte) constructor and no data is getting copied. MS simply stores a reference to the same array.

In fact, you made it worse because you pinned the array. Getting a garbage collection to run inside the body of your snippet isn’t unlikely, you are reading stuff from the array and are probably creating objects from the data, strings and what-not. The garbage collector needs to work around the pinned array, making its life considerably more difficult. This can actually affect the perf of your program for a while, compacting the heap is important to make the CPU cache efficient.

Leave a Comment