Golang原生map实现原理

目录

结构

初始化

赋值

1. 一切都顺利/已存在key但空间够

 2. 使用溢出桶

3. 扩容

取值 - 单个、迭代

删除 

结构

  • map
// Map contains Type fields specific to maps.
type Map struct {
	Key  *Type // Key type
	Elem *Type // Val (elem) type

	Bucket *Type // internal struct type representing a hash bucket
	Hmap   *Type // internal struct type representing the Hmap (map header object)
	Hiter  *Type // internal struct type representing hash iterator state
}

对外表现的类型Map,所有的field都是指针型

  • hmap - a header for a Go map
// A header for a Go map
type hmap struct {
	count     int // # live cells == size of map.  Must be first (used by len() builtin)
	flags     uint8 //0- 1-there may be an iterator using buckets 2 - there may be an iterator using oldbuckets 4 - a goroutine is writing to the map  8 - the current map growth is to a new map of the same size
	B         uint8  // 桶的数量2^B, log_2 of # of buckets (can hold up to loadFactor * 2^B items)
	noverflow uint16 // approximate number of overflow buckets; see incrnoverflow for details
	hash0     uint32 // hash seed

	buckets    unsafe.Pointer // array of 2^B Buckets. may be nil if count==0. hiter
	oldbuckets unsafe.Pointer // previous bucket array of half the size, non-nil only when growing
	nevacuate  uintptr        // progress counter for evacuation (buckets less than this have been evacuated)

	extra *mapextra // optional fields,存储溢出信息
}
  1. count为函数len()的值 ,所以len时间复杂度为O(1)
  2. flags用于标记当前map的状态   —— 0 -> 正常;1 -> 有迭代器正在使用buckets,buckets为结构里第6个field;2 -> 有迭代器正在使用oldbuckets, oldbuckets为第7个field;4 -> 有goroutine正在往里写数据;8 -> 当成map正在扩展成一个相同尺寸的map
  3. B,桶个数,2^B个桶

  4. noverflow,(number of overflow),overflow桶的大致数量

  5. hash0, hash种子

  6. buckets,存放map键值对,是一个bucket数组,当count=0时这个值为nil

  7. oldbuckets,上面buckets数量的一半,map增长的时候使用,不在增长期时为nil

  8. nevacuate,(number of evacuate),map增长的时候使用

  9. extra,存储溢出信息,结构如下,当buckets空间使用完后并不会马上扩空间,会允许存放一定量的键值对到mapextra里
// mapextra holds fields that are not present on all maps.
type mapextra struct {
	overflow    *[]*bmap
	oldoverflow *[]*bmap

	// nextOverflow holds a p
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值