Notes

Friday, June 10, 2022

Performance of TimeZoneInfo.FindSystemTimeZoneById(...)

According to the documentation:

This method returns a new TimeZoneInfo instance for each method call; it does not return cached objects. This may impact performance in applications that call the FindSystemTimeZoneById method repeatedly with the same identifier.

To avoid performance problems with FindSystemTimeZoneById, TimeZoneInfo instances should probably be cached in a service like this registered as a singleton:

public class TimeZoneInfoCache
{
    private readonly ConcurrentDictionary<string, TimeZoneInfo> cache = new(StringComparer.OrdinalIgnoreCase);

    public TimeZoneInfo FindSystemTimeZoneById(string id)
    {
        ArgumentNullException.ThrowIfNull(id);

        return cache.GetOrAdd(id, TimeZoneInfo.FindSystemTimeZoneById);
    }
}