Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 815
David Hamilton Avatar asked Jan 05 '11 21:01

David Hamilton


People also ask

What is the difference between Stream and MemoryStream?

You would use the FileStream to read/write a file but a MemoryStream to read/write in-memory data, such as a byte array decoded from a string. You would not use a Stream in and of itself, but rather use it for polymorphism, i.e. passing it to methods that can accept any implementation of Stream as an argument.

What is the use of MemoryStream?

MemoryStream encapsulates data stored as an unsigned byte array that is initialized upon creation of a MemoryStream object, or the array can be created as empty. The encapsulated data is directly accessible in memory. Memory streams can reduce the need for temporary buffers and files in an application.

Does MemoryStream copy byte array?

From expirience I can say, that it does not copy the array. Be aware though, that you are unable to resize the memory stream, when using an array in the constructor.

What is MemoryStream C#?

MemoryStream in C# programs allows you to use in-memory byte arrays or other data as though they are streams. Instead of storing data in files, you can store data in-memory.


1 Answers

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.

like image 75
iammichael Avatar answered Sep 18 '22 17:09

iammichael