Remove StringBuilder from HebrewNumber formatting by stephentoub · Pull Request #21122 · dotnet/coreclr (original) (raw)

Rather than allocating a new StringBuilder, writing into that, getting its string, and then appending that string to another StringBuilder, we can just write directly to the original one.

cc: @tarekgh

[MemoryDiagnoser] [InProcess] public class Test { private static CultureInfo _hebrewIsrael;

[Benchmark] public string FormatHebrew() => new DateTime(2018, 11, 20).ToString(_hebrewIsrael);

public static void Main()
{
    _hebrewIsrael = new CultureInfo("he-IL");
    _hebrewIsrael.DateTimeFormat.Calendar = new HebrewCalendar();
    BenchmarkRunner.Run<Test>();
}

}

Before:

       Method |     Mean |    Error |   StdDev |  Gen 0 | Allocated |
------------- |---------:|---------:|---------:|-------:|----------:|
 FormatHebrew | 750.8 ns | 11.00 ns | 10.29 ns | 0.1421 |     600 B |

After:

       Method |     Mean |    Error |   StdDev |  Gen 0 | Allocated |
------------- |---------:|---------:|---------:|-------:|----------:|
 FormatHebrew | 618.2 ns | 10.32 ns | 8.619 ns | 0.0772 |     328 B |