Skip to content

Stream.ReadByte should use stackalloc byte[1] instead allocate one byte array #68800

@DrkWzrd

Description

@DrkWzrd

Description

In advance sorry for my english and sorry if this "is not a bug".

Right now in System.IO.Stream.ReadByte the code allocates an 1-length array for return the only byte read done in Read(byte[], int, int)

public virtual int ReadByte()
{
var oneByteArray = new byte[1];
int r = Read(oneByteArray, 0, 1);
return r == 0 ? -1 : oneByteArray[0];
}

Reproduction Steps

Just that.

Expected behavior

public virtual int ReadByte()
{
    var oneByteArray = (stackalloc byte[1]);
    int r = Read(oneByteArray);
    return r == 0 ? -1 : oneByteArray[0];
}

Actual behavior

Actually a call to ReadByte can produce unnecesary GCs (and some child classes and developers that are unaware of this use it a lot).

Regression?

No response

Known Workarounds

No response

Configuration

No response

Other information

No response

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions