Sobes.tech
Senior

How does map differ from sync.Map?

sobes.tech AI

Answer from AI

map in Go is a built-in data type for storing key-value pairs, but it is not thread-safe. Concurrent access from multiple goroutines without synchronization can lead to data races and panics.

sync.Map is a specialized structure from the sync package that provides thread-safe access to data without the need for external locking.

Main differences:

  • Thread safety: map requires external synchronization (e.g., using sync.Mutex), sync.Map is built-in.
  • API: sync.Map has methods Load, Store, LoadOrStore, Delete, Range, whereas a regular map uses bracket notation.
  • Performance: sync.Map is optimized for scenarios with frequent reads and infrequent writes. For intensive writes, a regular map with a mutex might be faster.

Example of using sync.Map:

var m sync.Map

// Store
m.Store("key", "value")

// Load
if val, ok := m.Load("key"); ok {
    fmt.Println(val)
}

// Delete
m.Delete("key")

// Iterate
m.Range(func(k, v interface{}) bool {
    fmt.Println(k, v)
    return true
})

Choose a map with a mutex if you have complex logic and many writes, and sync.Map if you need to quickly and simply ensure thread safety for predominantly read data.