sync.Map and map+Mutex are two approaches to thread-safe data storage.
1// sync.Map: optimized for read-heavy scenarios2var m sync.Map34// Write5m.Store("key", "value")67// Read8val, ok := m.Load("key")9if ok {10 fmt.Println(val.(string))11}1213// Atomic operation14actual, loaded := m.LoadOrStore("key", "default")1516// Range (non-blocking)17m.Range(func(key, value interface{}) bool {18 fmt.Printf("%v: %v\n", key, value)19 return true // true = continue20})2122// map + Mutex: general purpose23type SafeMap struct {24 mu sync.RWMutex25 m map[string]string26}2728func (s *SafeMap) Get(key string) (string, bool) {29 s.mu.RLock()30 defer s.mu.RUnlock()31 val, ok := s.m[key]32 return val, ok33}3435func (s *SafeMap) Set(key, value string) {36 s.mu.Lock()37 defer s.mu.Unlock()38 s.m[key] = value39}4041// Performance comparison42func BenchmarkSyncMapRead(b *testing.B) {43 var m sync.Map44 m.Store("key", "value")45 for i := 0; i < b.N; i++ {46 m.Load("key")47 }48}4950func BenchmarkMutexMapRead(b *testing.B) {51 m := map[string]string{"key": "value"}52 var mu sync.RWMutex53 for i := 0; i < b.N; i++ {54 mu.RLock()55 _ = m["key"]56 mu.RUnlock()57 }58}
When to use sync.Map:
When to use map+Mutex: