[Mono-dev] Should we replace MemoryStream?

Robert Jordan robertj at gmx.net
Tue Nov 10 11:24:56 EST 2009


Avery Pennarun wrote:
> On Tue, Nov 10, 2009 at 8:48 AM, Robert Jordan <robertj at gmx.net> wrote:
>> MemoryStream.GetBuffer's docs indirectly suggest that no copy
>> will be performed:
>> "Note that the buffer contains allocated bytes which might be unused.
>> For example, if the string "test" is written into the MemoryStream
>> object, the length of the buffer returned from GetBuffer is 256, not 4,
>> with 252 bytes unused. To obtain only the data in the buffer, use the
>> ToArray method; however, ToArray creates a copy of the data in memory."
>> So MemoryStream.GetBuffer must remain an O(1) operation in any case,
>> defeating any kind of optimization a chunked memory stream
>> implementation may introduce.
> Although this might be strictly true if you want to react exactly as
> Microsoft's documentation claims (I thought 100% compatibility with
> .Net was not the primary goal of mono?), there may be other options
> that result in similar performance

Right, but MemoryStream is pretty prevalent and one of its frequent
usage pattern is:

var ms = new MemoryStream () or MemoryStream(somepredictedsize);
// fill ms with some stream APIs
ms.Close ();
var bytes = ms.GetBuffer ();
// pass `bytes' to byte[] APIs (e.g. unmanaged world)

> For example, the first call to GetBuffer() could "coagulate" the
> chunks into a single big array (perhaps with extra space at the end),
> and then *keep that array*.  Subsequent calls to GetBuffer() could
> avoid the copy.

GetBuffer () is usually called only once per instance.


More information about the Mono-devel-list mailing list