Middle
What is sync.Map and when should it be used instead of a regular map with Mutex?
sobes.tech AI
Answer from AI
sync.Map is a thread-safe implementation of a map in Go, optimized for scenarios with frequent read operations and infrequent writes. Unlike a regular map with a Mutex, it uses internal mechanisms to reduce locking during reads.
You should use sync.Map when:
- There are many concurrent reads and few writes.
- You cannot predetermine the keys or their number.
If you have many writes or complex update logic, a regular map with a Mutex might be more efficient and easier to understand.
Example of using sync.Map:
var m sync.Map
// Write
m.Store("key", "value")
// Read
if val, ok := m.Load("key"); ok {
fmt.Println(val)
}
// Delete
m.Delete("key")