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

Improve speed of Randomizer.GetString #4512

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
19 changes: 14 additions & 5 deletions src/NUnitFramework/framework/Internal/Randomizer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Runtime.CompilerServices;

namespace NUnit.Framework.Internal
{
Expand Down Expand Up @@ -501,12 +502,20 @@ public T NextEnum<T>()
/// <returns>A random string of arbitrary length</returns>
public string GetString(int outputLength, string allowedChars)
{
var data = new char[outputLength];
#if NET6_0_OR_GREATER
return string.Create(outputLength, allowedChars, FillSpan);
#else
Span<char> data = stackalloc char[outputLength];
FillSpan(data, allowedChars);

for (int i = 0; i < data.Length; i++)
data[i] = allowedChars[Next(0, allowedChars.Length)];

return new string(data);
return data.ToString()!;
#endif
[MethodImpl(MethodImplOptions.AggressiveInlining)]
void FillSpan(Span<char> data, string allowedChars)
{
for (int i = 0; i < data.Length; i++)
data[i] = allowedChars[Next(0, allowedChars.Length)];
}
}

/// <summary>
Expand Down
1 change: 1 addition & 0 deletions src/NUnitFramework/framework/nunit.framework.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
<ItemGroup>
<PackageReference Include="Nullable" Version="1.3.1" PrivateAssets="all" />
<PackageReference Include="IsExternalInit" Version="1.0.3" PrivateAssets="all" />
<PackageReference Include="System.Memory" Version="4.5.5" />
</ItemGroup>

<ItemGroup Condition="'$(TargetFramework)' == 'netstandard2.0'">
Expand Down