Counting number of items in a concurrent map

Lately I’ve been using Go’s concurrent map. And sometimes I needed to count the items I’ve stored in the map. I have ranged over the items and incremented a counter, and it was done:

package main

import (
       "sync"
       "log"
)

func main() {
       m := sync.Map{}
       
       m.Store("k1", "v1")
       m.Store("k2", "v2")
       
       count := 0
       m.Range(func(key, value interface{}) bool{
              count++
              return true
       })

       log.Println(count)
}

But I didn’t want to range over the items each time I wanted to count them. So I thought of incrementing the counter every time an element was added, and to decrementing it when one was removed. The following is just for practice, I didn’t perform any advanced tests. Continue reading Counting number of items in a concurrent map