I had the same issue to solve with the requirement of appending a specific count instead of the whole array, and my first solution was the same as suggested by Hugo. But my feeling said "inefficient" because of that many resizes.
Then I remembered that the StringBuilder
is capacity-optimized. As next I asked myself, does it apply to MemoryStream
too. After some tries I can say yes it does.
The MemoryStream
starts with a minimal capacity of 256 bytes and grows if necessary by the double of its last capacity, like 256, 512, 1024, 2048, 4096, 8192 and so on.
My next question was, how long it takes to do array resize and copy in contrast to using a MemoryStream
. Using a MemoryStream
was much faster instead of array resize and copy.
Hence, I guess using a MemoryStream
is the most efficient way.