Potential optimizations for BufferedReadStream.ReadLine
- Dominant language
- C#
- Stars
- 38.4k
- Forks
- 10.9k
- Avg merge
- 2d 10h
- Merged PRs (30d)
- 281
Description
### Is there an existing issue for this?
- [X] I have searched the existing issues
### Is your feature request related to a problem? Please describe the problem.
1. `BufferedReadStream.ReadLine`'s main loop essentially walks over every single byte in the array and checks whether it's `CR` (or `LF`). This can be rewritten with `Span.IndexOf` to first find `CR` and if that succeeds, check whether the next byte is `LF`.
https://github.com/dotnet/aspnetcore/blob/678a06f95aced0d4c6f837e53cfc6ffdbb7362b9/src/Http/WebUtilities/src/BufferedReadStream.cs#L356-L363
https://github.com/dotnet/aspnetcore/blob/678a06f95aced0d4c6f837e53cfc6ffdbb7362b9/src/Http/WebUtilities/src/BufferedReadStream.cs#L398-L410
2. While decoding byte array to string `MemoryStream.ToArray` is called. The issue with it is that it's going to copy the internal array. Instead, this can be changed to `MemoryStream.GetBuffer`, which returns the internal buffer.
https://github.com/dotnet/aspnetcore/blob/678a06f95aced0d4c6f837e53cfc6ffdbb7362b9/src/Http/WebUtilities/src/BufferedReadStream.cs#L416
### Describe the solution you'd like
Reduce allocations from `BufferedReadStream.DecodeLine` (p. 2). This should be safe as `MemoryStream` is created by the `BufferedReadStream` itself and only used locally.
Optimizing `BufferedReadStream.ReadLine` main loop (p. 1) would also be nice, though not that simple (for example, there is a possible case when the last byte in the buffer is `CR`, but checking whether the next byte is `LF` is impossible without reading from a stream).
### Additional context
_No response_
Contributor guide
Assessment
This issue has not been assessed yet.