Question

When I write some stream into a new memory stream, the length and capacity of the memory stream are both set to 0 at first, and grow along with the write process. but at some point the capacity grows faster than the length.
After the write operation is done I get the correct length (Same as the original input stream's length), but with MUCH bigger capacity.
Is it correct?
Shouldn't they be the same?
I couldn't find any info about it

Was it helpful?

Solution

Shouldn't they be the same?

No - or at least, not necessarily. This is basically the same as a List<T>'s capacity vs its count (or StringBuilder for that matter). The idea is that in order to minimize the number of times you make a copy, when you need to increase your capacity, you increase it significantly - not just by one byte at a time. So for example, one strategy would be "Minimum of 16 bytes, and double the capacity when you need to."

After you've done some write operations, how is the stream meant to know that you're finished? And would you really want it to have to copy the entire contents in order to perform a write of one more byte?

Basically the trade-off is memory vs speed: the larger you make the capacity, the more writing you can do quickly between copies.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top