# Improving DateTime Cache

In one of the [previous posts](https://blog.ladeak.net/posts/net11-perf-imp-07.md), 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.CompareExchange` is known to be more efficient than `Lock`, 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.

## Using a Struct

One improvement opportunity from the original version was replacing the reference type `CachedTime`, which represented a cache item, with a struct. That would remove one level of indirection, and because both `int` and `DateTime` are value types, it would also slightly reduce the working set. However, `Interlocked.CompareExchange` does not work with custom structs. Fortunately, both the year and the `DateTime` can be represented as a `long`. This is not a safe operation, but bit casting is possible with `Unsafe.BitCast<long, DateTime>`. That means implicitly relying on some of the internals of `DateTime`, and bit casting is dangerous because it can create `DateTime` values that otherwise would not be valid under `DateTime` preconditions. For example, the value `3652059 * TimeSpan.TicksPerDay` corresponds to `01/01/10000`, but creating `new DateTime(10000, 1, 1)` throws an `ArgumentOutOfRangeException` in .NET 11. This seemingly odd limitation turns out to be useful later on.

Instead of having an array of references, a `long[]` can store all values. Indices from `[0..29]` store the keys, and the values are stored at an offset of 30, in indices `[30..59]`.

The next challenge is the `Interlocked.CompareExchange` call. Reference types can use `null` to indicate that an index is unused, so the `comparand` argument can be `null`. However, if we used the default `0` value of the `long` type, we could not cache `01/01/0001`. This is where the invalid `DateTime` value comes in handy, because it can serve as the default value of each index, representing the case where no value has been set yet.

Finally, the code has to set the `DateTime` value at one index and the key for the year at another. Updating these two indices is not atomic. This may leave some performance on the table if two threads set the same value and one of them is blocked before updating the key index. Otherwise, the code uses memory barriers to ensure an updated value is read and written in the correct order.

## Code

This is the second version of `TimeParserInterlocked`. The code is for demonstration purposes only; please do not use it in production.

```csharp
public class TimeParserInterlocked
{
    private const long U = 3652059 * TimeSpan.TicksPerDay; // UnrepresentableTicks
    private const int HalfLength = 30;
    private readonly long[] _cache = [0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0, U,U,U,U, U,U,U,U, U,U,U,U, U,U,U,U, U,U,U,U, U,U,U,U, U,U,U,U, U,U];

    public DateTime GetDateTime(int year)
    {
        Span<long> span = _cache.AsSpan(0, HalfLength);
        for (int i = HalfLength - 1; i >= 0; i--)
        {
            var value = Volatile.Read(ref span[i]);
            if (value == year)
                return Unsafe.BitCast<long, DateTime>(_cache[i + HalfLength]);
            else if (value == 0)
                return SlowPath(year, i);
        }
        return default;
    }

    private DateTime SlowPath(int year, int offset)
    {
        var entry = Unsafe.BitCast<DateTime, long>(new DateTime(year, 1, 1));
        for (int i = HalfLength + offset; i >= HalfLength; i--)
        {
            var oldValue = Interlocked.CompareExchange(ref _cache[i], entry, U);
            if (oldValue == U) // Success, new item added to the cache, now update the lower half
            {
                Volatile.Write(ref _cache[i - HalfLength], year);
                return Unsafe.BitCast<long, DateTime>(entry);
            }
            else if (oldValue == entry)
                return Unsafe.BitCast<long, DateTime>(entry);
        }
        throw new InvalidOperationException();
    }
}
```

## Assembly

As described in the previous post, the performance of the solution greatly depends on many environmental factors:

- number of concurrent read/write threads
- the cost of creating the `DateTime` value (there may be more complex logic to determine the year, month, and day values)
- platform (x64 vs. arm64)
- number of reads over the lifetime of the application
- number of distinct values

In my measurements, this solution was slightly more performant than the reference based solution. The assembly code is very similar, and I have left comments in the assembly to make it easier to follow.

```assembly
G_M000_IG03:                ;; offset=0x0020
       mov      r9, qword ptr [rax+8*r8]
       cmp      r9, r10 // 👈 Compares the array index with the input year.
       je       SHORT G_M000_IG10

G_M000_IG04:                ;; offset=0x0029
       test     r9, r9 // 👈 Check is the current array index is zero.
       je       SHORT G_M000_IG08

G_M000_IG05:                ;; offset=0x002E
       dec      r8d // 👈 Decrements the loop variable.
       jns      SHORT G_M000_IG03
```

Compared to the [previous solution](https://blog.ladeak.net/posts/net11-perf-imp-07.md), it has one less `cmp` instruction because the loop iterates toward zero, and it avoids an additional dereference by using value types instead of reference types.

There are still some unexplored opportunities for this code, but they would be unlikely to help with the critical loop:

- using inlined arrays
- possible vectorization in the lookup loop
- reducing false sharing by spreading keys and values in memory

## Conclusion

While improving this method is a lot of fun, I would not recommend using it in production applications because of the unresolved edge cases. The performance gains are far outweighed by the additional code complexity and unsafe operations.