Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reusing Memory Streams

Tags:

c#

Assume I have copied a byte buffer into a memory stream using this

memoryStream.Read(data, 0, data.Length);

Is there any way for me to empty the stream and reuse it to read additional data?

I want to avoid creating many MemoryStream objects and prefer to use one instance, resetting it between usages

like image 731
Jack Kada Avatar asked Apr 24 '11 08:04

Jack Kada


People also ask

How do I reuse a memory stream?

You can re-use the MemoryStream by Setting the Position to 0 and the Length to 0. By setting the length to 0 you do not clear the existing buffer, it only resets the internal counters.

What is MemoryStream flush?

A MemoryStream writes to RAM so the whole concept of buffering and flushing is redundant. The data is always in RAM already. And yes, disposing the stream will cause it to be flushed. Follow this answer to receive notifications.

What are memory streams?

MemoryStream encapsulates data stored as an unsigned byte array. The encapsulated data is directly accessible in memory. Memory streams can reduce the need for temporary buffers and files in an application. The current position of a stream is the position at which the next read or write operation takes place.


2 Answers

You can re-use the MemoryStream by Setting the Position to 0 and the Length to 0.

MemoryStream ms = new MemoryStream();  // Do some stuff with the stream  // Reset the stream so you can re-use it ms.Position = 0; // Not actually needed, SetLength(0) will reset the Position anyway ms.SetLength(0);  // Do some more stuff with the stream 

By setting the length to 0 you do not clear the existing buffer, it only resets the internal counters. So the existing buffer allocation remains intact, but all the book keeping of how much of the buffer is used is reset so that you can re-use it.

Update: I just took a quick look at the code implementation for SetLength and if you set the length to 0 the Position will automatically be reset to 0 so you do not even need to explicitly set the Position property it is enough to just reset the length.

like image 165
Chris Taylor Avatar answered Sep 20 '22 03:09

Chris Taylor


You can set the Position to 0, this will in effect reset the stream.

However, as this answer indicates, reusing memory streams will not likely gain you any performance benefits. It is cheaper to create more memory streams.

Another option it to use a pinned byte[] as your buffer for reuse.

like image 35
Oded Avatar answered Sep 19 '22 03:09

Oded