Streamline primality cache locking

This commit is contained in:
Marek Lemańczyk committed 2025-10-16 21:52:42 +02:00
1 parent 8d9b8b1829
commit d2e7e4905a
1 file changed
+19 -30
+19 -30
View File
@@ -795,48 +795,37 @@ internal static partial class PrimeOrderCalculator
private static bool TryGetCachedPrimality(ulong value, out bool isPrime) private static bool TryGetCachedPrimality(ulong value, out bool isPrime)
{ {
Dictionary<ulong, bool>? cache = Volatile.Read(ref _primalityCache); _primalityCacheLock.EnterReadLock();
if (cache is null) try
{ {
isPrime = default; Dictionary<ulong, bool>? cache = _primalityCache;
return false; if (cache is null)
} {
isPrime = default;
return false;
}
return cache.TryGetValue(value, out isPrime); return cache.TryGetValue(value, out isPrime);
}
finally
{
_primalityCacheLock.ExitReadLock();
}
} }
private static void CachePrimalityResult(ulong value, bool isPrime) private static void CachePrimalityResult(ulong value, bool isPrime)
{ {
Dictionary<ulong, bool>? cache = Volatile.Read(ref _primalityCache);
if (cache is not null && cache.TryGetValue(value, out bool existing) && existing == isPrime)
{
return;
}
_primalityCacheLock.EnterWriteLock(); _primalityCacheLock.EnterWriteLock();
try try
{ {
Dictionary<ulong, bool>? current = _primalityCache; Dictionary<ulong, bool>? cache = _primalityCache;
if (current is null) if (cache is null)
{ {
Dictionary<ulong, bool> newCache = new() cache = new Dictionary<ulong, bool>();
{ _primalityCache = cache;
[value] = isPrime,
};
Volatile.Write(ref _primalityCache, newCache);
return;
} }
if (current.TryGetValue(value, out bool existingValue) && existingValue == isPrime) cache[value] = isPrime;
{
return;
}
Dictionary<ulong, bool> updated = new(current)
{
[value] = isPrime,
};
Volatile.Write(ref _primalityCache, updated);
} }
finally finally
{ {