NorthWind
NorthWind

Reputation:

MemoryStream vs an array of bytes

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.

Upvotes: 8

Views: 7521

Answers (2)

Mike Dinescu
Mike Dinescu

Reputation: 55760

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..

Upvotes: 3

Christopher
Christopher

Reputation: 9094

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.

Upvotes: 4

Related Questions