runtime icon indicating copy to clipboard operation
runtime copied to clipboard

Performance of Stream.Read(Span<byte> buffer) and Stream.ReadByte()

Open DevAM-Tools opened this issue 1 year ago • 1 comments

Description

In my experience APIs that use Spans are introduce for performance reasons. (as a rule of thumb) Accordingly I would assume that Stream.Read(Span<byte> buffer) offers a better performance than Stream.Read(byte[] buffer, int offset, int count).

If I take a look on the code of Stream.Read(Span buffer) it looks quite inefficient when looking for good performance. There is a second Buffer rented from the ArrayPool which the actual data is written to and after that the data is copied to the target buffer.

It might be counter intuitive for some people taking the experience into account that people might have with Span-APIs. (See introduction above)

On top of that when looking on Stream.ReadByte() there is an allocation of an 1 byte array for every byte that is read via this method. I would have expected the usage of a preallocated array or the usage of stackalloc in such a scenario.

DevAM-Tools avatar Jan 15 '25 18:01 DevAM-Tools

The base Stream.Read(Span) implementation must be implemented in terms of the Stream.Read(byte[], ...) method, as that array-based method is what a derived type is required to implement; the span method was later added as a virtual, and needed to be implemented in terms of the existing method so that someone then calling it gets functionally-equivalent behavior.

However, for anyone concerned with performance, these base implementations should / will almost never be used. Types deriving from Stream should / do override these methods to provide an optimized implementation for the purposes of that derived type. If you look at effectively all of the concrete Stream-derived types in dotnet/runtime, for example, you'll find they all override these methods.

For ReadByte specifically, see https://github.com/dotnet/runtime/issues/111206.

stephentoub avatar Jan 15 '25 18:01 stephentoub