Why would you use sync.Map instead of a standard map with a sync.RWMutex, and in what access patterns does sync.Map perform better?
Last updated
Default to a plain map guarded by sync.RWMutex: it is simpler, type-safe, and faster for most workloads, especially write-heavy or balanced ones.
sync.Mapwins in two patterns: write-once/read-many keys, and goroutines working on mostly disjoint key sets. Its lock-free read map lets hot reads skip locking.Costs: keys/values are
any(no compile-time type safety), plus higher memory use and worse write-heavy performance. Benchmark before adopting.
- https://elsyarifx.medium.com/gos-sync-map-is-not-what-you-think-and-when-you-should-use-it-anyway-11d719f1e27a
- https://stackoverflow.com/questions/59299470/working-with-slices-and-golang-sync-map-structure
- https://stackoverflow.com/questions/61355008/is-sync-map-the-right-tool-for-this-use-case-or-is-a-rw-mutex-lock-better