Performance: use a BinaryReader in a MemoryStream to read an array of bytes or read directly?

I would like to know if using a BinaryReader in a MemoryStream created from an array of bytes ( byte[] ) can significantly reduce performance.

There is binary data that I want to read, and I get this data as an array of bytes. I am currently deciding between two approaches to reading data and should accordingly implement a variety of reading methods. After each reading action, I need a position immediately after the data being read, and therefore I am considering using BinaryReader . The first, non-BinaryReader approach:

 object Read(byte[] data, ref int offset); 

Second approach:

 object Read(BinaryReader reader); 

Such Read() methods will be called very often, sequentially from the same data, until all the data has been read.

So, using BinaryReader seems more natural, but does it have a big impact on performance?

+4
source share
2 answers

You will create enough garbage for each Read (byte []) call. There will be 40 bytes for MemoryStream, I stopped reading 64 bytes for BinaryReader. Dispose is also commonly used, although it does nothing. Is it impossible for overhead questions to answer your question.

I would prefer an overload of Read (BinaryReader), not just because it is more efficient. It also gives flexibility in changing the data source. It should no longer be in the byte [], you can feed it, say, FileStream or NetworkStream.

+2
source

If using BinaryReader seems more natural, do it. I highly doubt that there are any notable performance gains against reading from an array.

-1
source

Source: https://habr.com/ru/post/1312652/


All Articles