From d2e7e4905a281fac50a77ad7e879bb1fef4bb919 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marek=20Lema=C5=84czyk?= Date: Thu, 16 Oct 2025 21:52:42 +0200 Subject: [PATCH] Streamline primality cache locking --- PerfectNumbers.Core/PrimeOrderCalculator.cs | 49 ++++++++------------- 1 file changed, 19 insertions(+), 30 deletions(-) diff --git a/PerfectNumbers.Core/PrimeOrderCalculator.cs b/PerfectNumbers.Core/PrimeOrderCalculator.cs index 6493d6d..1f205cd 100644 --- a/PerfectNumbers.Core/PrimeOrderCalculator.cs +++ b/PerfectNumbers.Core/PrimeOrderCalculator.cs @@ -795,48 +795,37 @@ internal static partial class PrimeOrderCalculator private static bool TryGetCachedPrimality(ulong value, out bool isPrime) { - Dictionary? cache = Volatile.Read(ref _primalityCache); - if (cache is null) + _primalityCacheLock.EnterReadLock(); + try { - isPrime = default; - return false; - } + Dictionary? cache = _primalityCache; + 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) { - Dictionary? cache = Volatile.Read(ref _primalityCache); - if (cache is not null && cache.TryGetValue(value, out bool existing) && existing == isPrime) - { - return; - } - _primalityCacheLock.EnterWriteLock(); try { - Dictionary? current = _primalityCache; - if (current is null) + Dictionary? cache = _primalityCache; + if (cache is null) { - Dictionary newCache = new() - { - [value] = isPrime, - }; - Volatile.Write(ref _primalityCache, newCache); - return; + cache = new Dictionary(); + _primalityCache = cache; } - if (current.TryGetValue(value, out bool existingValue) && existingValue == isPrime) - { - return; - } - - Dictionary updated = new(current) - { - [value] = isPrime, - }; - Volatile.Write(ref _primalityCache, updated); + cache[value] = isPrime; } finally {