Skip to content

SqlBytes.Stream should consider overriding Span Read/Write methods #69921

@eerhardt

Description

@eerhardt

SqlBytes.Stream can return a custom Stream class StreamOnSqlBytes and returns it to external callers. Since .NET Core 2.1, System.IO.Stream has had Read and Write overloads that accept a Span to read to / write from. However, the base Stream implementation isn't optimized. To get the best performance when a caller is using the Span-based APIs, derived implementations of Stream are expected to override the Span-based APIs and perform the operation on the Spans. See the System.IO.Stream section of #22387 for more information.

We should consider overriding the Span Read/Write methods on StreamOnSqlBytes:

// The Read/Write/ReadByte/WriteByte simply delegates to SqlBytes
public override int Read(byte[] buffer, int offset, int count)
{
CheckIfStreamClosed();
ValidateBufferArguments(buffer, offset, count);
int iBytesRead = (int)_sb.Read(_lPosition, buffer, offset, count);
_lPosition += iBytesRead;
return iBytesRead;
}
public override void Write(byte[] buffer, int offset, int count)
{
CheckIfStreamClosed();
ValidateBufferArguments(buffer, offset, count);
_sb.Write(_lPosition, buffer, offset, count);
_lPosition += count;
}

That way callers using the Span-based APIs get better performance - an ArrayPool buffer doesn't need to be rented, and the data copied twice.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions