Skip to content

Commit

Permalink
Use a fast modulo algorithm to calculate the bucket (#60)
Browse files Browse the repository at this point in the history
  • Loading branch information
rockdaboot authored Nov 13, 2024
1 parent fffe46d commit df0880f
Showing 1 changed file with 7 additions and 1 deletion.
8 changes: 7 additions & 1 deletion lru.go
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,13 @@ func (lru *LRU[K, V]) hashToBucketPos(hash uint32) uint32 {
if lru.mask != 0 {
return hash & lru.mask
}
return hash % lru.size
return fastModulo(hash, lru.size)
}

// fastModulo calculates x % n without using the modulo operator (~4x faster).
// Reference: https://lemire.me/blog/2016/06/27/a-fast-alternative-to-the-modulo-reduction/
func fastModulo(x, n uint32) uint32 {
return uint32((uint64(x) * uint64(n)) >> 32) //nolint:gosec
}

// hashToPos converts a key into a position in the elements array.
Expand Down

0 comments on commit df0880f

Please sign in to comment.