views:

659

answers:

2

Hi;

While using a MemoryStream, I find myself often copying (hence duplicating) data to a temporary array of bytes.

I think it's a little bit of a waste of ressource, because MemoryStream dosen't let you directly access the underlying byte array.

In this situation, what's the real advantage of a MemoryStream? I have read somewhere that it acts like a memory-mapped file. Data is brought from disk only on access, consuming less memory.

Is that true? I don't think so. Maybe it's the case for a FileStream?

Thank you for your clarification.

+2  A: 

For me, the primary advantage of a memory stream is that it grows dynamically, and is optimized to do so. It is a pain to have to copy it out and duplicate memory, but if you primary use of it is to construct a buffer to be handed off at the end of the process, that flaw is amortized somewhat.

I should add, as opposed to a FileStream, MemoryStreams are much, much faster. They are more limited in size than FileStreams, because you generally have vastly more disk space than RAM. So you have to decide whether you need speed or space.

Christopher
Well, in both case (MemoryStream or FileStream), the Read and Write methods take a integer for offset and count. So I think they can go up to the same size.
They theoretically can, but remember that MemoryStream is stored in Memory, so when the RAM is full, it starts to page, and this will cause application slowdowns, and after a while, system slowdowns (due to RAM and page being full).
Andrew Moore
Yep, one funny thing I noticed is that the Length property of a stream is a long (8 bytes). You can't even reference a file that big with the Read and Write methods. I am pretty sure it has something to do with the native win32 API.
+2  A: 

You can get the underlying byte buffer using the getBuffer function (but only if you created the MemoryStream from a byte array that you provided, which is useful if you want to be able to manipulate the buffer directly)

The only advantage to using a MemoryStream is if you're using an API that's based on streams, of if you need the byte buffer to be able to grow dynamically..

Miky Dinescu