aaubry / YamlDotNet

YamlDotNet is a .NET library for YAML
MIT License
2.58k stars 484 forks source link

Eliminate allocs in TypeConverterCache lookup path #969

Closed MattKotsenas closed 2 months ago

MattKotsenas commented 2 months ago

Switching the TypeConverterCache from a Dictionary to a ConcurrentDictionary accidentally re-introduced a Func<T> allocation on every .GetOrAdd() call.

Remove that allocation in the hot path by calling LookupTypeConverter statically. This saves ~5MB of allocations in the serialization benchmark.

Before

Method Job Runtime Mean Error StdDev Gen0 Gen1 Gen2 Allocated
Serializer MediumRun-.NET 8.0 .NET 8.0 41.14 ms 1.280 ms 1.876 ms 1500.0000 500.0000 - 19.02 MB
Serializer MediumRun-.NET Framework 4.7 .NET Framework 4.7 118.00 ms 6.116 ms 8.965 ms 6600.0000 600.0000 200.0000 41.34 MB

After

Method Job Runtime Mean Error StdDev Gen0 Gen1 Gen2 Allocated
Serializer MediumRun-.NET 8.0 .NET 8.0 39.80 ms 1.457 ms 2.181 ms 1000.0000 500.0000 - 14.45 MB
Serializer MediumRun-.NET Framework 4.7 .NET Framework 4.7 116.52 ms 5.888 ms 8.813 ms 5800.0000 600.0000 200.0000 36.75 MB
EdwardCooke commented 2 months ago

Awesome, thanks for the additional performance improvement work.