From d352fef61febf4f16ba1cb3aee2259b73705e89d Mon Sep 17 00:00:00 2001 From: Nick Craver Date: Wed, 20 May 2020 14:20:06 -0400 Subject: [PATCH] MemoryCache: Reduce DateTime.UtcNow calls In a few MemoryCache hot paths, we're doing a syscall to get the time twice. It's far from ideal since the cost is a significant portion of the overall time. This is step 1, minor and non-breaking for ~30% gains in performance. --- .../src/MemoryCache.cs | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/src/libraries/Microsoft.Extensions.Caching.Memory/src/MemoryCache.cs b/src/libraries/Microsoft.Extensions.Caching.Memory/src/MemoryCache.cs index bcce0ebb80e5ac..9e58fb6903bba0 100644 --- a/src/libraries/Microsoft.Extensions.Caching.Memory/src/MemoryCache.cs +++ b/src/libraries/Microsoft.Extensions.Caching.Memory/src/MemoryCache.cs @@ -222,7 +222,7 @@ private void SetEntry(CacheEntry entry) } } - StartScanForExpiredItems(); + StartScanForExpiredItems(utcNow); } /// @@ -257,7 +257,7 @@ public bool TryGetValue(object key, out object result) } } - StartScanForExpiredItems(); + StartScanForExpiredItems(utcNow); return found; } @@ -306,9 +306,10 @@ private void EntryExpired(CacheEntry entry) // Called by multiple actions to see how long it's been since we last checked for expired items. // If sufficient time has elapsed then a scan is initiated on a background task. - private void StartScanForExpiredItems() + private void StartScanForExpiredItems(DateTimeOffset? utcNow = null) { - var now = _options.Clock.UtcNow; + // Since fetching time is expensive, minimize it in the hot paths + var now = utcNow ?? _options.Clock.UtcNow; if (_options.ExpirationScanFrequency < now - _lastExpirationScan) { _lastExpirationScan = now;