New Memory Allocation with MemoryStream.ToArray()

Posted by nhughes Thu, 05 May 2005 09:43:59 GMT

If you find that you need to reduce your frequent memory allocations and deallocations, try to reduce or eliminate your use of MemoryStream.ToArray(). ToArray() copies the memory stream buffer into a new byte array. You might consider using MemoryStream.GetBuffer() instead. This method returns the byte array inside the MemoryStream, instead of making a copy.

Note: GetBuffer() returns the entire array that was originally allocated, which is probably much larger than the data you wrote. You'll need to use the MemoryStream's Length property to pick your data out of the array.

Comments are disabled