Skip to content

Commit bf77f79

Browse files
committed
Reworked compact which shaved off 2 seconds off when calling SetAll with 1m items.
1 parent 48ce79e commit bf77f79

File tree

1 file changed

+15
-6
lines changed

1 file changed

+15
-6
lines changed

src/Foundatio/Caching/InMemoryCacheClient.cs

Lines changed: 15 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -715,7 +715,7 @@ private async Task<bool> SetInternalAsync(string key, CacheEntry entry, bool add
715715
if (isTraceLogLevelEnabled) _logger.LogTrace("Set cache key: {Key}", key);
716716
}
717717

718-
await StartMaintenanceAsync(true).AnyContext();
718+
await StartMaintenanceAsync(ShouldCompact).AnyContext();
719719
return wasUpdated;
720720
}
721721

@@ -957,18 +957,22 @@ private async Task StartMaintenanceAsync(bool compactImmediately = false)
957957
if (compactImmediately)
958958
await CompactAsync().AnyContext();
959959

960-
if (TimeSpan.FromMilliseconds(100) < utcNow - _lastMaintenance)
960+
if (TimeSpan.FromMilliseconds(250) < utcNow - _lastMaintenance)
961961
{
962962
_lastMaintenance = utcNow;
963963
_ = Task.Run(DoMaintenanceAsync);
964964
}
965965
}
966966

967+
private bool ShouldCompact => _maxItems.HasValue && _memory.Count > _maxItems;
968+
967969
private async Task CompactAsync()
968970
{
969-
if (!_maxItems.HasValue || _memory.Count <= _maxItems)
971+
if (!ShouldCompact)
970972
return;
971973

974+
_logger.LogTrace("CompactAsync: Compacting cache");
975+
972976
string expiredKey = null;
973977
using (await _lock.LockAsync().AnyContext())
974978
{
@@ -1014,7 +1018,11 @@ private async Task DoMaintenanceAsync()
10141018
foreach (var kvp in _memory.ToArray())
10151019
{
10161020
bool lastAccessTimeIsInfrequent = kvp.Value.LastAccessTicks < lastAccessMaximumTicks;
1017-
if (lastAccessTimeIsInfrequent && kvp.Value.ExpiresAt < DateTime.MaxValue && kvp.Value.ExpiresAt <= utcNow)
1021+
if (!lastAccessTimeIsInfrequent)
1022+
continue;
1023+
1024+
var expiresAt = kvp.Value.ExpiresAt;
1025+
if (expiresAt < DateTime.MaxValue && expiresAt <= utcNow)
10181026
{
10191027
_logger.LogDebug("DoMaintenance: Removing expired key {Key}", kvp.Key);
10201028
RemoveKeyIfExpired(kvp.Key);
@@ -1023,10 +1031,11 @@ private async Task DoMaintenanceAsync()
10231031
}
10241032
catch (Exception ex)
10251033
{
1026-
_logger.LogError(ex, "Error trying to find expired cache items");
1034+
_logger.LogError(ex, "Error trying to find expired cache items: {Message}", ex.Message);
10271035
}
10281036

1029-
await CompactAsync().AnyContext();
1037+
if (ShouldCompact)
1038+
await CompactAsync().AnyContext();
10301039
}
10311040

10321041
public void Dispose()

0 commit comments

Comments
 (0)