Skip to content

Conversation

@BrennanConroy
Copy link
Member

No description provided.

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.

4 participants