I have a byte array which can be a couple MB in size that I am writing to a MemoryStream
. One of the constructors for MemoryStream
allows me to set the capacity of the MemoryStream
so it doesn’t have to be resized (new allocation and copied) as it’s being written to which would make it run faster. It seems like I should set the capacity since I know the length of the byte array but I can’t find any examples of this being done online so I was wondering if there’s something I’m missing here? Would the below code make sense?
byte[] bytes = <bytes from somewhere>;
using (var memoryStream = new MemoryStream(bytes.Length)) // is there any reason I shouldn't do this?
{
memoryStream.Write(bytes, 0, bytes.Length);
memoryStream.Position = 0;
// do stuff with the memoryStream
}