Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Optimize Random{NumberGenerator}.GetItems for power-of-two choices #92229

Merged
merged 6 commits into from
Sep 19, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions src/libraries/System.Private.CoreLib/src/System/Random.cs
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Buffers;
using System.Diagnostics;
using System.Numerics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

namespace System
{
Expand Down Expand Up @@ -194,6 +197,38 @@ public void GetItems<T>(ReadOnlySpan<T> choices, Span<T> destination)
throw new ArgumentException(SR.Arg_EmptySpan, nameof(choices));
}

// The most expensive part of this operation is the call to get random data. We can
// do so potentially many fewer times if:
// - the number of choices is <= 256. This let's us get a single byte per choice.
// - the number of choices is a power of two. This let's us use a byte and simply mask off
// unnecessary bits cheaply rather than needing to use rejection sampling.
// In such a case, we can grab a bunch of random bytes in one call.
if (BitOperations.IsPow2(choices.Length) && choices.Length <= 256)
{
Span<byte> randomBytes = stackalloc byte[512]; // arbitrary size, a balance between stack consumed and number of random calls required
stephentoub marked this conversation as resolved.
Show resolved Hide resolved
while (!destination.IsEmpty)
{
if (destination.Length < randomBytes.Length)
{
randomBytes = randomBytes.Slice(0, destination.Length);
}

NextBytes(randomBytes);

int mask = choices.Length - 1;
for (int i = 0; i < randomBytes.Length; i++)
{
destination[i] = choices[randomBytes[i] & mask];
}

destination = destination.Slice(randomBytes.Length);
}

return;
}

// Simple fallback: get each item individually, generating a new random Int32 for each
// item. This is slower than the above, but it works for all types and sizes of choices.
for (int i = 0; i < destination.Length; i++)
{
destination[i] = choices[Next(choices.Length)];
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using System.Buffers;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Numerics;
using System.Runtime.InteropServices;

namespace System.Security.Cryptography
Expand Down Expand Up @@ -350,6 +351,41 @@ private static void GetHexStringCore(Span<char> destination, bool lowercase)

private static void GetItemsCore<T>(ReadOnlySpan<T> choices, Span<T> destination)
{
// The most expensive part of this operation is the call to get random data. We can
// do so potentially many fewer times if:
// - the number of choices is <= 256. This let's us get a single byte per choice.
// - the number of choices is a power of two. This let's us use a byte and simply mask off
// unnecessary bits cheaply rather than needing to use rejection sampling.
// In such a case, we can grab a bunch of random bytes in one call.
if (BitOperations.IsPow2(choices.Length) && choices.Length <= 256)
{
// Get stack space to store random bytes. This size was chosen to balance between
// stack consumed and number of random calls required.
Span<byte> randomBytes = stackalloc byte[512];

while (!destination.IsEmpty)
{
if (destination.Length < randomBytes.Length)
{
randomBytes = randomBytes.Slice(0, destination.Length);
}

RandomNumberGeneratorImplementation.FillSpan(randomBytes);

int mask = choices.Length - 1;
for (int i = 0; i < randomBytes.Length; i++)
{
destination[i] = choices[randomBytes[i] & mask];
}

destination = destination.Slice(randomBytes.Length);
}

return;
}

// Simple fallback: get each item individually, generating a new random Int32 for each
// item. This is slower than the above, but it works for all types and sizes of choices.
for (int i = 0; i < destination.Length; i++)
{
destination[i] = choices[GetInt32(choices.Length)];
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -669,9 +669,12 @@ public static void GetItems_Int_NoDeduplication()
public static void GetString_RandomDistribution()
{
const string Choices = "abcdefghijklmnopqrstuvwxyz";
string generated = RandomNumberGenerator.GetString(Choices, 10_000);
VerifyDistribution<char>(generated, 1f / 26);
VerifyAllInRange(generated, 'a', (char)('z' + 1));
for (int i = 1; i <= Choices.Length; i++)
{
string generated = RandomNumberGenerator.GetString(Choices.AsSpan(0, i), 10_000);
VerifyDistribution<char>(generated, 1f / i);
VerifyAllInRange(generated, 'a', (char)('a' + i));
}
}

[Fact]
Expand Down