- Micro-optimize
Mapfor integer keys #185 - Add
Map.RangeRelaxedmethod for faster map iteration #187 - Add
Map.DeleteMatchingmethod for batch entry deletion #186
Read-heavy operations on Map with integer keys are now 24-29% faster due to a more efficient hash function, as well as a number of micro-optimizations.
RangeRelaxed is a much faster (~11x), lock-free alternative to Range. The downside is that the same key may be visited by RangeRelaxed more than once if it is concurrently deleted and re-inserted during the iteration. RangeRelaxed should be preferred over Range in all cases when weaker consistency is acceptable.
m := xsync.NewMap[string, int]()
m.Store("alice", 10)
m.Store("bob", 20)
m.Store("carol", 30)
m.Store("dave", 40)
// Iterate map entries and calculate sum of all values.
sum := 0
m.RangeRelaxed(func(key string, value int) bool {
sum += value
return true // continue iteration
})DeleteMatching deletes all entries for which the delete return value of the input function is true. If the cancel return value is true, the iteration stops immediately. The function returns the number of deleted entries. The call locks a hash table bucket for the duration of evaluating the function for all entries in the bucket and performing deletions. It performs up to 20% faster than Range + Delete, yet if the percentage of the entries to-be-deleted is low, RangeRelaxed + Delete combination should be more efficient.
// Delete entries with value greater than 25.
deleted := m.DeleteMatching(func(key string, value int) (delete, cancel bool) {
return value > 25, false
})