.NET MemoryStream - Should I set the capacity?

故事扮演 提交于 2019-11-30 01:03:07

问题


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?


回答1:


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.




回答2:


Old question I know, but just for the record;

If you are dealing with a really large amount of data (more than one GB in my case), setting the initial capacity was the only way to make it work in an acceptable period of time and without killing the server. In this scenario the re-sizing overhead was crucial.




回答3:


If you know the size you're going to need, I believe setting the size explicitly will improve performance, because the framework won't have to resize the stream several times.




回答4:


If you know already exactly how many bytes you want to store setting it explicitly in the constructor seems the right thing - In general I would keep it as simple as possible and just use the default constructor with no parameters, it's just one more thing you have to read and understand when maintaining the code otherwise.




回答5:


If you know that you will nee 0x10000 bytes of data, the first code snippet ensures that the memory stream is initialized to this size and will never need to increase. There might be some performance implications depending on how the class manages the buffer underneath and whether it needs a contiguous block of memory; depending on the specifics, resizing might be an expensive operation.




回答6:


In first case you avoid automatic structure resize cost while needed size is less than value passed to constructor.




回答7:


When a memory stream is re-sized, it creates a new byte[] buffer of new size. If this operation is being performed frequently, you can face one of two problems depending on buffer size: 1. The system throws OurOfMemoryException 2. All memory in the heap gets fragmented. It gives unpredictable consequences. For example constructor of System.Drawing.Bitmap fails with 'Parameter is not valid' message.



来源:https://stackoverflow.com/questions/4609445/net-memorystream-should-i-set-the-capacity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!