Sobes.tech
Middle

How does map work under the hood in the new versions of Go, what has changed?

sobes.tech AI

Answer from AI

In newer versions of Go (starting from Go 1.9 and later), the internal structure of maps has been significantly improved to enhance performance and reduce memory fragmentation.

Main changes:

  • Open addressing hash table with chaining: maps are now implemented as a hash table with an array of buckets, where each bucket contains multiple elements. In case of collisions, elements are stored in a linked list within the bucket.
  • Growth optimization: When the size of the map increases, elements are gradually redistributed (incremental rehashing), which reduces pauses and improves responsiveness.
  • Improved data locality: Elements within buckets are stored compactly, enhancing cache performance.
  • Protection against attacks: Randomization of the hash function has been added to prevent DoS attacks via collisions.

Example of using a map in Go:

m := make(map[string]int)
m["apple"] = 5
value, ok := m["apple"]
if ok {
    fmt.Println("Value:", value)
}

When adding a key, the hash is computed, a bucket is selected, and the element is inserted. When the fill threshold is reached, the map expands with redistribution of elements.

How does map work under the hood in the new versions… - sobes.tech