Improve TimeSpan.ToString/TryFormat throughput for default format by stephentoub · Pull Request #18990 · dotnet/coreclr (original) (raw)

Improves the throughput of the null/"c"/"t"/"T" default format for TimeSpan.ToString/TryFormat, porting over the approach/specialization from Utf8Formatter.

Contributes to https://github.com/dotnet/corefx/issues/30612
cc: @jkotas, @danmosemsft, @ahsonkhan

Benchmark:

using System; using BenchmarkDotNet.Attributes; using BenchmarkDotNet.Attributes.Jobs; using BenchmarkDotNet.Running;

[MemoryDiagnoser] [InProcess] public class Benchmark { private static void Main() => BenchmarkRunner.Run();

private TimeSpan _simple = new TimeSpan(1, 2, 3);
private TimeSpan _maxValue = new TimeSpan(long.MaxValue);
private char[] _tmp = new char[100];

[Benchmark] public string SimpleToString() => _simple.ToString();
[Benchmark] public bool SimpleTryFormat() => _simple.TryFormat(_tmp, out int charsWritten);

[Benchmark] public string MaxToString() => _maxValue.ToString();
[Benchmark] public bool MaxTryFormat() => _maxValue.TryFormat(_tmp, out int charsWritten);

}

Before/After:

Benchmark Before (ns) After (ns) Improvement
SimpleToString 126.8 44.76 2.83x
SimpleTryFormat 147.2 30.25 4.87x
MaxToString 391.9 111.56 3.51x
MaxTryFormat 282.7 106.23 2.66x