From 30c655f1dd2368d22ed4e29854fd79923e639914 Mon Sep 17 00:00:00 2001 From: Charlie Tonneslan Date: Sun, 31 May 2026 08:52:26 -0400 Subject: [PATCH] shard: skip hashmapStats allocation when stats are disabled initNewShard always built a hashmapStats map even when StatsEnabled was false. #420 cut the capacity hint to 0 for that case, but make still returned a real empty map per shard, so the default Config still paid for an unused map header on every shard. All hashmapStats writes (hit, hitWithoutLock, del) are already guarded by s.statsEnabled, and the reads in getKeyMetadata{,WithLock} return the zero value of uint32 for a nil map, which is what they'd return for a missing key anyway. Leaving hashmapStats nil when stats are off is behaviour-preserving. Closes #422 Signed-off-by: Charlie Tonneslan --- shard.go | 19 +++++++++---------- 1 file changed, 9 insertions(+), 10 deletions(-) diff --git a/shard.go b/shard.go index 1549ad9..321dc91 100644 --- a/shard.go +++ b/shard.go @@ -437,16 +437,11 @@ func initNewShard(config Config, callback onRemoveCallback, clock clock) *cacheS if maximumShardSizeInBytes > 0 && bytesQueueInitialCapacity > maximumShardSizeInBytes { bytesQueueInitialCapacity = maximumShardSizeInBytes } - var hashmapStatsCapacity int - if config.StatsEnabled { - hashmapStatsCapacity = config.initialShardSize() - } - return &cacheShard{ - hashmap: make(map[uint64]uint64, config.initialShardSize()), - hashmapStats: make(map[uint64]uint32, hashmapStatsCapacity), - entries: *queue.NewBytesQueue(bytesQueueInitialCapacity, maximumShardSizeInBytes, config.Verbose), - entryBuffer: make([]byte, config.MaxEntrySize+headersSizeInBytes), - onRemove: callback, + shard := &cacheShard{ + hashmap: make(map[uint64]uint64, config.initialShardSize()), + entries: *queue.NewBytesQueue(bytesQueueInitialCapacity, maximumShardSizeInBytes, config.Verbose), + entryBuffer: make([]byte, config.MaxEntrySize+headersSizeInBytes), + onRemove: callback, isVerbose: config.Verbose, logger: newLogger(config.Logger), @@ -455,4 +450,8 @@ func initNewShard(config Config, callback onRemoveCallback, clock clock) *cacheS statsEnabled: config.StatsEnabled, cleanEnabled: config.CleanWindow > 0, } + if config.StatsEnabled { + shard.hashmapStats = make(map[uint64]uint32, config.initialShardSize()) + } + return shard }