Golang map internal implementation - how does it search the map for a key?

前端 未结 2 1129
借酒劲吻你
借酒劲吻你 2020-12-15 08:21

I\'ve read in "The Go Programming Language" that a "given key can be retrieved ... using a constant number of key comparisons on average, no matter how large

2条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-15 08:52

    Maps are implemented as hash tables. There are plenty of places that explain hashing; Here's a nice visualization you can run.

    One nice feature of Go is that

    • the source is available on github, and
    • it is pretty well written and documented, so it's not too hard to understand.

    From the source file for hashmap:

    // A map is just a hash table. The data is arranged
    // into an array of buckets. Each bucket contains up to
    // 8 key/value pairs. The low-order bits of the hash are
    // used to select a bucket. Each bucket contains a few
    // high-order bits of each hash to distinguish the entries
    // within a single bucket.
    //
    // If more than 8 keys hash to a bucket, we chain on
    // extra buckets.
    

    https://github.com/golang/go/blob/master/src/runtime/map.go

    One thing that you can learn from this code that is not normally covered in a lot of classes is how not to invalidate iterators when the map is resized internally.

提交回复
热议问题