Search code examples
.netmemorystream

.NET MemoryStream - Should I set the capacity?


This is probably a really simple question, I think all that I am after is Best Practice for declaring a new MemoryStream

What is the difference between the following 2 samples:

MemoryStream myStream = new MemoryStream(0x10000);

or

MemoryStream myStream = new MemoryStream();

Obviously, I know that the first example set the initial capacity of the stream. But, both of these have an automatically resizable capacity.

I there any reason why I should use one method as opposed to the other?


Solution

  • There is overhead associated with re-sizing a memory stream. If you know or otherwise have a reasonable guess as to the expected size needed to be stored in the memory stream, you'll want to use that size as the initial capacity. Otherwise, the default size of 0 is used and will be resized as data is added.