@@ -298,21 +298,34 @@ func (l *localCacheImpl[K, V]) expireEntries() {
298298
299299// pruneEntries goes through the map to see if any entries have expired or size is reached and remove them.
300300func (l * localCacheImpl [K , V ]) pruneEntries () {
301- currentCacheSize := int64 (len (l .data ))
301+ var (
302+ currentCacheSize = int64 (len (l .data ))
303+ currentCacheMemory = l .cacheMemory
304+ )
302305
303306 l .expireEntries ()
304307
305308 start := time .Now ()
306309
307- // if highUnits or highUnitsMemory are set then check
308- if (l .options .HighUnits > 0 && currentCacheSize + 1 > l .options .HighUnits ) ||
309- (l .options .HighUnitsMemory > 0 && l .cacheMemory + 1 > l .options .HighUnitsMemory ) {
310+ highUnitsPrune := l .options .HighUnits > 0 && currentCacheSize + 1 > l .options .HighUnits
311+ highUnitsMemoryPrune := l .options .HighUnitsMemory > 0 && currentCacheMemory + 1 > l .options .HighUnitsMemory
310312
313+ // if highUnits or highUnitsMemory are set then check
314+ if highUnitsPrune || highUnitsMemoryPrune {
311315 defer func () {
312316 l .registerPruneNanos (time .Since (start ).Nanoseconds ())
313317 }()
314318
315- entriesToDelete := int (math .Round (float64 (float32 (currentCacheSize ) * (1 - l .options .PruneFactor ))))
319+ var (
320+ entriesToDelete = - 1
321+ targetMemory int64 = - 1
322+ )
323+
324+ if highUnitsPrune {
325+ entriesToDelete = int (math .Round (float64 (float32 (currentCacheSize ) * (1 - l .options .PruneFactor ))))
326+ } else {
327+ targetMemory = int64 (math .Round (float64 (float32 (currentCacheMemory ) * l .options .PruneFactor )))
328+ }
316329
317330 // prune to default of l.options.PruneFactor % of the cache size.
318331 // we first sort the map by lastAccess time / then insert time, so we remove all
@@ -336,9 +349,11 @@ func (l *localCacheImpl[K, V]) pruneEntries() {
336349 sort .Sort (sortData )
337350
338351 for i , v := range sortData {
339- if i > entriesToDelete {
352+ // break if we have reached the high units or memory prune target
353+ if (highUnitsPrune && i > entriesToDelete ) || (highUnitsMemoryPrune && l .cacheMemory <= targetMemory ) {
340354 break
341355 }
356+
342357 l .updateEntrySize (l .data [v .key ], - 1 )
343358 atomic .AddInt64 (& l .cacheEntriesPruned , 1 )
344359 l .removeExpiry (v .key )
0 commit comments