Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Arrays vs. Streams

When writing functions that operate on a potentially infinite "stream" of data, i.e. bytes, chars, whatever, what are some design considerations in deciding to use Strings/Arrays vs. Streams for the input/output?

Is there a huge performance impact of always writing functions to use streams, and then making overload methods that use stream wrappers (i.e. StringReader/Writer) to return "simple data" like an array or a string that doesnt require disposing and other considerations?

I would think functions operating on arrays are far more convenient because you can "return" a resulting array and you don't usually have to worry about disposing. I assume stream operators are nice because they can operate on an infinite source of data, probably memory-efficient as well.

like image 882
Martin Bliss Avatar asked Dec 05 '25 15:12

Martin Bliss


2 Answers

If you are working with binary data of unknown size always use streams. Reading an entire file into a byte array for example is usually bad idea if it can be avoided. Most functions in .Net that work with binary data such as encryption and compression are built to use streams as input/output.

like image 116
Magnus Avatar answered Dec 08 '25 04:12

Magnus


If you are writing a function to process a stream of data, then why not pass it as an IEnumerable<T>. You can then return a stream as an IEnumerable<T> in a generator function. In other words using return yield to return each result one a ta time.

You can end up with asymptotic improvements in performance in some cases because the evaluation is done as needed.

like image 25
cdiggins Avatar answered Dec 08 '25 04:12

cdiggins



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!