Use sync.Map for high-concurrency, read-heavy scenarios to avoid the performance penalty of locking a standard map.
Use sync.Map when you need a thread-safe map for high-concurrency read-heavy workloads without the overhead of a global lock. Initialize it with var m sync.Map and use Store, Load, and Delete methods for operations.
package main
import (
"fmt"
"sync"
)
func main() {
var m sync.Map
// Store a value
m.Store("key", "value")
// Load a value
if val, ok := m.Load("key"); ok {
fmt.Println(val) // Output: value
}
// Delete a value
m.Delete("key")
}
sync.Map is a special map designed for situations where many parts of your program need to read data at the same time, but only a few need to change it. Unlike a regular map, it doesn't lock the entire map for every operation, making it much faster for read-heavy tasks. Think of it like a library where most people are just reading books (fast), but only a few are checking books in or out (slower, but handled efficiently).