I am working on a golang project where tree nodes are stored in a map for quick access. Writes to the map will never happen concurrently (and for each key, they only happen once), but I would like to read concurrently with both reads/writes. I've been reading about both sync.Map and simply using RWMutex locks, but I am unsure which one is better for this use case (or if there is a 3rd party package that solves this problem). Does anybody have a recommendation on an approach/have any resources for reading up on the different options? Thank you!
Start with using sync.Map
. It's simpler than rolling your own, and will likely be faster.
The Map type is optimized for two common use cases: (1) when the entry for a given key is only ever written once but read many times, as in caches that only grow, or (2) when multiple goroutines read, write, and overwrite entries for disjoint sets of keys. In these two cases, use of a Map may significantly reduce lock contention compared to a Go map paired with a separate Mutex or RWMutex.
Case (1) in this quote (from the official docs of sync.Map
) sound like exactly what you need.
If you end up being unhappy with the performance over time, benchmark it and replace the slow part with a faster solution (if possible).
© 2022 - 2024 — McMap. All rights reserved.
sync.Map
quite clearly explain when it's beneficial to use over a regular map with your own locking or coordination: The Map type is optimized for two common use cases: (1) when the entry for a given key is only ever written once but read many times, as in caches that only grow, or (2) when multiple goroutines read, write, and overwrite entries for disjoint sets of keys. – Chalicesync.Map
is the right tool for the job then – Selfwill