Skip to content
Merged
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
20 changes: 9 additions & 11 deletions src/libraries/System.Private.CoreLib/src/System/Random.cs
Original file line number Diff line number Diff line change
Expand Up @@ -363,18 +363,16 @@ public void Shuffle<T>(T[] values)
/// </remarks>
public void Shuffle<T>(Span<T> values)
{
int n = values.Length;

for (int i = 0; i < n - 1; i++)
for (int i = 0; i < values.Length - 1; i++)
{
int j = Next(i, n);

if (j != i)
{
T temp = values[i];
values[i] = values[j];
values[j] = temp;
}
int j = Next(i, values.Length);

// The i != j check is excluded intentionally.
// Microbenchmarks show that the mispredicted branches cost more than the redundant read/write for small value types.
// Since large value types are uncommon in shuffle scenarios, the trade-off favors removing the branch.
T temp = values[i];
values[i] = values[j];
values[j] = temp;
}
}

Expand Down