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 StringBuilder usage #44691

Merged
merged 2 commits into from
Oct 24, 2022
Merged

Improve StringBuilder usage #44691

merged 2 commits into from
Oct 24, 2022

Conversation

BrennanConroy
Copy link
Member

No description provided.

@@ -64,7 +64,7 @@ private string GenerateAppSecretProof(string accessToken)
var builder = new StringBuilder();
for (int i = 0; i < hash.Length; i++)
{
builder.Append(hash[i].ToString("x2", CultureInfo.InvariantCulture));
builder.Append(CultureInfo.InvariantCulture, $"{hash[i]:x2}");
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

FYI @martincostello and @javiercn in regards to the conversation at https://github.com/dotnet/aspnetcore/pull/36368/files#r706039158

This makes use of Interpolated string handlers, and StringBuilder has a custom one which allows formatting the interpolated string directly into it's internal buffer instead of instantiating a string then copying the string.

Method Mean Error StdDev Gen0 Allocated
AppendToString 748.7 ns 12.33 ns 10.93 ns 0.1841 1448 B
AppendInterpolated 739.7 ns 9.29 ns 8.23 ns 0.0620 488 B
Benchmark code
[MemoryDiagnoser]
public class AppendBenchmark
{
    private byte[] _b = new byte[30];

    [GlobalSetup]
    public void Setup()
    {
        RandomNumberGenerator.Fill(_b);
    }

    [Benchmark]
    public string AppendToString()
    {
        var sb = new StringBuilder();
        foreach (var b in _b)
        {
            sb.Append(b.ToString("x2", CultureInfo.InvariantCulture));
        }
        return sb.ToString();
    }

    [Benchmark]
    public string AppendInterpolated()
    {
        var sb = new StringBuilder();
        foreach (var b in _b)
        {
            sb.Append(CultureInfo.InvariantCulture, $"{b:x2}");
        }
        return sb.ToString();
    }
}

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice 😎

@BrennanConroy BrennanConroy marked this pull request as ready for review October 24, 2022 16:08
@BrennanConroy BrennanConroy merged commit 8fa956f into main Oct 24, 2022
@BrennanConroy BrennanConroy deleted the brecon/stringbuilder branch October 24, 2022 20:17
@ghost ghost added this to the 8.0-preview1 milestone Oct 24, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants