Improving DateTime Cache12/01/2026
In one of the previous posts, I explored how .NET 11 uses a copy-on-write locking strategy for caching function pointers and how other locking strategies could be used as an alternative. In that post I used an example, that is intentionally artificial: a DateTime GetDateTime(int year) method returns a specific DateTime value for a given year, representing January 1 of that year.
I used the Interlocked pattern with a constraint on the input: a maximum of 30 distinct entries were allowed. This let me preallocate a backing array for all possible values and use Interlocked.CompareExchange to atomically replace the default values of the array with the cached entries. The conclusion of that post said:
Interlocked.CompareExchangeis known to be more efficient thanLock, but the gains are quickly offset by external factors. [...] The copy-on-write strategy remains a flexible and performant choice for similar problems.
This post looks into improving that solution. The code presented here is not safe to use in production.