Skip to content

[.NET 6] Improving the default Random.NextInt64 performance for derived classes #57272

@koszeggy

Description

@koszeggy

Description

Consider a pre-.NET 6 library used from .NET 6 that has a derived Random class but doesn't override the NextInt64 methods (example).

As such a class has no overridden NextInt64 methods, the internal Net5CompatImpl implementation kicks in, whose private NextUInt64 method ends up calling the Next() method 8 times for each byte in the ulong sample to be generated.

Proposed fix

Please consider changing the current NextUInt64 method like this:

private unsafe ulong NextUInt64()
{
    Span<byte> resultBytes = stackalloc byte[8];
    _parent.NextBytes(resultBytes); // instead of: NextBytes(resultBytes);
    return BitConverter.ToUInt64(resultBytes);
}

The proposed change above calls the possibly overridden NextBytes(Span<byte>) overload, which gives a chance for a pre-.NET 6 class to fill up the buffer much more efficiently. If NextBytes(Span<byte>) is not overridden either, then this eventually calls the current Net5CompatImpl implementation with those repeated Next calls.

Risks

This will produce different results from the current implementation but since .NET 6 is not released yet I don't think it's a real issue.

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions