Home > Article > Backend Development > Data structure in go-detailed explanation of dictionary map
1. Use of map
map in golang is a data type that binds keys and values Together, the bottom layer is implemented using a hash table, and the corresponding value can be quickly found through the key.
Type representation: map[keyType][valueType] key must be a comparable type (can be understood as supporting == operation), and value can be of any type.
Initialization: map can only be initialized using make. When declared, it defaults to a nil map. At this time, the value is retrieved and a zero value of the corresponding type is returned (zero value is returned if it does not exist). Adding elements makes no sense and can cause runtime errors. Assigning to an uninitialized map causes panic: assign to entry in nil map.
package main import ( "fmt" ) // bool 的零值是false var m map[int]bool a, ok := m[1] fmt.Println(a, ok) // false false // int 的零值是0 var m map[int]int a, ok := m[1] fmt.Println(a, ok) // 0 false func main() { var agemap[string]int if age== nil { fmt.Println("map is nil.") age= make(map[string]int) } }
Clear the map: For a collection exp with certain data, the way to clear it is to initialize it again: exp = make(map[string]int). If the map is no longer used later, you can directly: exp = nil, but if it needs to be reused, make initialization must be performed, otherwise nothing can be added to the nil map.
Properties: Like slices, map is a reference type. When a map is assigned to a new variable, they both point to the same internal data structure. So changes to one will be reflected in the other. When used as a formal parameter or return parameter, a copy of the address is passed, and this address will not be changed during expansion.
func main() { exp := map[string]int{ "steve": 20, "jamie": 80, } fmt.Println("Ori exp", age) newexp:= exp newexp["steve"] = 18 fmt.Println("exp changed", exp) } //Ori age map[steve:20 jamie:80] //age changed map[steve:18 jamie:80]
Traverse the map: The map itself is unordered. When traversing, it will not be passed out in the order you passed in.
//正常遍历: for k, v := range exp { fmt.Println(k, v) } //有序遍历 import "sort" var keys []string // 把key单独抽取出来,放在数组中 for k, _ := range exp { keys = append(keys, k) } // 进行数组的排序 sort.Strings(keys) // 遍历数组就是有序的了 for _, k := range keys { fmt.Println(k, m[k]) }
2. The structure of map
The implementation of map in Go can be found in $GOROOT/src/runtime/map.go. Some key fields in the data structure of the hash table are as follows:
type hmap struct { count int //元素个数 flags uint8 B uint8 //扩容常量 noverflow uint16 //溢出 bucket 个数 hash0 uint32 //hash 种子 buckets unsafe.Pointer //bucket 数组指针 oldbuckets unsafe.Pointer //扩容时旧的buckets 数组指针 nevacuate uintptr //扩容搬迁进度 extra *mapextra //记录溢出相关 } type bmap struct { tophash [bucketCnt]uint8 // Followed by bucketCnt keys //and then bucketan Cnt values // Followed by overflow pointer. }
Description: The bottom layer of each map is the hmap structure, which consists of several elements describing the hmap structure, array pointers, Extra, etc., the buckets array pointer points to an array composed of several buckets. Each bucket stores key-value data (usually 8) and overflow fields (pointing to the next bmap). When each key is inserted, According to the hash algorithm, they are classified into the same bucket. When there are more than 8 elements in a bucket, hmap will use the overflow in extra to expand the storage key.
In the figure, len is the number of elements in the current map, which is the value returned by len(). It is also the value of hmap.count in the structure. Bucket array refers to an array pointer, pointing to the bucket array. hash seed hash seed. overflow points to the next bucket.
The bottom layer of map is mainly composed of three structures:
hmap --- the outermost data structure of map, including various basic information of map, such as size and bucket. A large structure.
mapextra --- Record additional information of the map, the structure pointed to by the extra pointer in the hmap structure, such as overflow bucket.
bmap --- represents bucket. Each bucket can hold up to 8 kvs. Finally, an overflow field points to the next bmap. Note that the key, value, and overflow fields are not defined, but the bias is calculated through maptype. Obtained by transfer.
The structure of mapextra is as follows
// mapextra holds fields that are not present on all maps. type mapextra struct { // If both key and value do not contain pointers and are inline, then we mark bucket // type as containing no pointers. This avoids scanning such maps. // However, bmap.overflow is a pointer. In order to keep overflow buckets // alive, we store pointers to all overflow buckets in hmap.extra.overflow and hmap.extra.oldoverflow. // overflow and oldoverflow are only used if key and value do not contain pointers. // overflow contains overflow buckets for hmap.buckets. // oldoverflow contains overflow buckets for hmap.oldbuckets. // The indirection allows to store a pointer to the slice in hiter. overflow *[]*bmap oldoverflow *[]*bmap // nextOverflow holds a pointer to a free overflow bucket. nextOverflow *bmap }
where hmap.extra.nextOverflow points to the pre-allocated overflow bucket. When the pre-allocated overflow bucket is used up, the value becomes nil.
The detailed structure of bmap is as follows
#When a hash conflict occurs in the map, bmap is first mounted with the minimum granularity, and one bmap accumulates After 8 kv, a new bmap (overflow bucket) will be applied for and hung behind this bmap to form a linked list. The pre-allocated overflow bucket will be used first. If the pre-allocated overflow bucket is used up, then malloc one will be hung. This reduces the number of objects and reduces the burden of memory management, which is beneficial to gc. Note that Golang's map will not shrink, the memory will only increase as it is used, and even if all the keys in the overflow bucket are deleted, they will not be released.
All keys in bmap exist in one block, and all values exist in one block. This facilitates memory alignment. When the key is larger than 128 bytes, the key field of the bucket stores a pointer pointing to the actual content of the key; the same is true for value.
The high 8 bits of the hash value are stored in the tophash field in the bucket. Each bucket can hold up to 8 kv pairs, so the tophash type is array [8] uint8. Store the upper eight bits so that non-matching keys can be filtered out without completely comparing the keys and speed up the query. In fact, when the high eight bits of the hash value are less than the constant minTopHash, minTopHash will be added, and the value in the interval [0, minTophash) is used for special marks. When searching for a key, calculate the hash value, use the high eight digits of the hash value to search in tophash, and if there is an equal tophash, compare the key values to see if they are the same.
type typeAlg struct { // function for hashing objects of this type // (ptr to object, seed) -> hash hash func(unsafe.Pointer, uintptr) uintptr // function for comparing objects of this type // (ptr to object A, ptr to object B) -> ==? equal func(unsafe.Pointer, unsafe.Pointer) bool // tophash calculates the tophash value for hash. func tophash(hash uintptr) uint8 { top := uint8(hash >> (sys.PtrSize*8 - 8)) if top < minTopHash { top += minTopHash } return top }
Golang defines the type descriptor _type for each type, and implements the hashable type _type.alg.hash and _type.alg.equal to support the map paradigm. It defines what hash function to use for this type of key, the size of the bucket, how to compare it, etc., and the paradigm is implemented through this variable.
3. Basic operations of map
3.1 Creation of map
//makemap为make(map [k] v,hint)实现Go map创建。 //如果编译器已确定映射或第一个存储桶,可以在堆栈上创建,hmap或bucket可以为非nil。 //如果h!= nil,则可以直接在h中创建map。 //如果h.buckets!= nil,则指向的存储桶可以用作第一个存储桶。 func makemap(t *maptype, hint int, h *hmap) *hmap { if hint < 0 || hint > int(maxSliceCap(t.bucket.size)) { hint = 0 } // 初始化Hmap if h == nil { h = new(hmap) } h.hash0 = fastrand() // 查找将保存请求的元素数的size参数 B := uint8(0) for overLoadFactor(hint, B) { B++ } h.B = B // 分配初始哈希表 // if B == 0, 稍后会延迟分配buckets字段(在mapassign中) //如果提示很大,则将内存清零可能需要一段时间。 if h.B != 0 { var nextOverflow *bmap h.buckets, nextOverflow = makeBucketArray(t, h.B, nil) if nextOverflow != nil { h.extra = new(mapextra) h.extra.nextOverflow = nextOverflow } } return h }
hint是一个启发值,启发初建map时创建多少个bucket,如果hint是0那么就先不分配bucket,lazy分配。大概流程就是初始化hmap结构体、设置一下hash seed、bucket数量、实际申请bucket、申请mapextra结构体之类的。
申请buckets的过程:
// makeBucketArray初始化地图存储区的后备数组。 // 1 << b是要分配的最小存储桶数。 // dirtyalloc之前应该为nil或bucket数组 //由makeBucketArray使用相同的t和b参数分配。 //如果dirtyalloc为零,则将分配一个新的支持数组,dirtyalloc将被清除并作为后备数组重用。 func makeBucketArray(t *maptype, b uint8, dirtyalloc unsafe.Pointer) (buckets unsafe.Pointer, nextOverflow *bmap) { base := bucketShift(b) nbuckets := base // 对于小b,溢出桶不太可能出现。 // 避免计算的开销。 if b >= 4 { //加上估计的溢出桶数 //插入元素的中位数 //与此值b一起使用。 nbuckets += bucketShift(b - 4) sz := t.bucket.size * nbuckets up := roundupsize(sz) if up != sz { nbuckets = up / t.bucket.size } } if dirtyalloc == nil { buckets = newarray(t.bucket, int(nbuckets)) } else { // dirtyalloc先前是由上面的newarray(t.bucket,int(nbuckets)),但不能为空。 buckets = dirtyalloc size := t.bucket.size * nbuckets if t.bucket.kind&kindNoPointers == 0 { memclrHasPointers(buckets, size) } else { memclrNoHeapPointers(buckets, size) } } if base != nbuckets { //我们预先分配了一些溢出桶。 //为了将跟踪这些溢出桶的开销降至最低,我们使用的约定是,如果预分配的溢出存储桶发生了溢出指针为零,则通过碰撞指针还有更多可用空间。 //对于最后一个溢出存储区,我们需要一个安全的非nil指针;只是用bucket。 nextOverflow = (*bmap)(add(buckets, base*uintptr(t.bucketsize))) last := (*bmap)(add(buckets, (nbuckets-1)*uintptr(t.bucketsize))) last.setoverflow(t, (*bmap)(buckets)) } return buckets, nextOverflow }
默认创建2b个bucket,如果b大于等于4,那么就预先额外创建一些overflow bucket。除了最后一个overflow bucket,其余overflow bucket的overflow指针都是nil,最后一个overflow bucket的overflow指针指向bucket数组第一个元素,作为哨兵,说明到了到结尾了。
3.2 查询操作
// mapaccess1返回指向h [key]的指针。从不返回nil,而是 如果值类型为零,它将返回对零对象的引用,该键不在map中。 //注意:返回的指针可能会使整个map保持活动状态,因此请不要坚持很长时间。 func mapaccess1(t *maptype, h *hmap, key unsafe.Pointer) unsafe.Pointer { if raceenabled && h != nil { //raceenabled是否启用数据竞争检测。 callerpc := getcallerpc() pc := funcPC(mapaccess1) racereadpc(unsafe.Pointer(h), callerpc, pc) raceReadObjectPC(t.key, key, callerpc, pc) } if msanenabled && h != nil { msanread(key, t.key.size) } if h == nil || h.count == 0 { return unsafe.Pointer(&zeroVal[0]) } // 并发访问检查 if h.flags&hashWriting != 0 { throw("concurrent map read and map write") } // 计算key的hash值 alg := t.key.alg hash := alg.hash(key, uintptr(h.hash0)) // alg.hash // hash值对m取余数得到对应的bucket m := uintptr(1)<<h.B - 1 b := (*bmap)(add(h.buckets, (hash&m)*uintptr(t.bucketsize))) // 如果老的bucket还没有迁移,则在老的bucket里面找 if c := h.oldbuckets; c != nil { if !h.sameSizeGrow() { m >>= 1 } oldb := (*bmap)(add(c, (hash&m)*uintptr(t.bucketsize))) if !evacuated(oldb) { b = oldb } } // 计算tophash,取高8位 top := uint8(hash >> (sys.PtrSize*8 - 8)) for { for i := uintptr(0); i < bucketCnt; i++ { // 检查top值,如高8位不一样就找下一个 if b.tophash[i] != top { continue } // 取key的地址 k := add(unsafe.Pointer(b), dataOffset+i*uintptr(t.keysize)) if alg.equal(key, k) { // alg.equal // 取value得地址 v := add(unsafe.Pointer(b), dataOffset+bucketCnt*uintptr(t.keysize)+i*uintptr(t.valuesize)) } } // 如果当前bucket没有找到,则找bucket链的下一个bucket b = b.overflow(t) if b == nil { // 返回零值 return unsafe.Pointer(&zeroVal[0]) } } }
先定位出bucket,如果正在扩容,并且这个bucket还没搬到新的hash表中,那么就从老的hash表中查找。
在bucket中进行顺序查找,使用高八位进行快速过滤,高八位相等,再比较key是否相等,找到就返回value。如果当前bucket找不到,就往下找overflow bucket,都没有就返回零值。
访问的时候,并不进行扩容的数据搬迁。并且并发有写操作时抛异常。
注意,t.bucketsize并不是bmap的size,而是bmap加上存储key、value、overflow指针,所以查找bucket的时候时候用的不是bmap的szie。
3.3 更新/插入过程
// 与mapaccess类似,但是如果map中不存在密钥,则为该密钥分配一个插槽 func mapassign(t *maptype, h *hmap, key unsafe.Pointer) unsafe.Pointer { ... //设置hashWriting调用alg.hash,因为alg.hash可能出现紧急情况后,在这种情况下,我们实际上并没有进行写操作. h.flags |= hashWriting if h.buckets == nil { h.buckets = newobject(t.bucket) // newarray(t.bucket, 1) } again: bucket := hash & bucketMask(h.B) if h.growing() { growWork(t, h, bucket) } b := (*bmap)(unsafe.Pointer(uintptr(h.buckets) + bucket*uintptr(t.bucketsize))) top := tophash(hash) var inserti *uint8 var insertk unsafe.Pointer var val unsafe.Pointer for { for i := uintptr(0); i < bucketCnt; i++ { if b.tophash[i] != top { if b.tophash[i] == empty && inserti == nil { inserti = &b.tophash[i] insertk = add(unsafe.Pointer(b), dataOffset+i*uintptr(t.keysize)) val = add(unsafe.Pointer(b), dataOffset+bucketCnt*uintptr(t.keysize)+i*uintptr(t.valuesize)) } continue } k := add(unsafe.Pointer(b), dataOffset+i*uintptr(t.keysize)) if t.indirectkey { k = *((*unsafe.Pointer)(k)) } if !alg.equal(key, k) { continue } // 已经有一个 mapping for key. 更新它. if t.needkeyupdate { typedmemmove(t.key, k, key) } val = add(unsafe.Pointer(b), dataOffset+bucketCnt*uintptr(t.keysize)+i*uintptr(t.valuesize)) goto done } ovf := b.overflow(t) if ovf == nil { break } b = ovf } //// 如果已经达到了load factor的最大值,就继续扩容。 //找不到键的映射。分配新单元格并添加条目。 //如果达到最大负载系数或溢出桶过多,并且我们还没有处于成长的中间,就开始扩容。 if !h.growing() && (overLoadFactor(h.count+1, h.B) || tooManyOverflowBuckets(h.noverflow, h.B)) { hashGrow(t, h) goto again // //扩大表格会使所有内容无效, so try again } if inserti == nil { // 当前所有存储桶已满,请分配一个新的存储桶 newb := h.newoverflow(t, b) inserti = &newb.tophash[0] insertk = add(unsafe.Pointer(newb), dataOffset) val = add(insertk, bucketCnt*uintptr(t.keysize)) } // 在插入的位置,存储键值 if t.indirectkey { kmem := newobject(t.key) *(*unsafe.Pointer)(insertk) = kmem insertk = kmem } if t.indirectvalue { vmem := newobject(t.elem) *(*unsafe.Pointer)(val) = vmem } typedmemmove(t.key, insertk, key) *inserti = top h.count++ done: if h.flags&hashWriting == 0 { throw("concurrent map writes") } h.flags &^= hashWriting if t.indirectvalue { val = *((*unsafe.Pointer)(val)) } return val }
hash表如果正在扩容,并且这次要操作的bucket还没搬到新hash表中,那么先进行搬迁(扩容细节下面细说)。
在buck中寻找key,同时记录下第一个空位置,如果找不到,那么就在空位置中插入数据;如果找到了,那么就更新对应的value;
找不到key就看下需不需要扩容,需要扩容并且没有正在扩容,那么就进行扩容,然后回到第一步。
找不到key,不需要扩容,但是没有空slot,那么就分配一个overflow bucket挂在链表结尾,用新bucket的第一个slot放存放数据。
3.5 删除的过程
func mapdelete(t *maptype, h *hmap, key unsafe.Pointer) { ... // Set hashWriting after calling alg.hash, since alg.hash may panic, // in which case we have not actually done a write (delete). h.flags |= hashWriting bucket := hash & bucketMask(h.B) if h.growing() { growWork(t, h, bucket) } b := (*bmap)(add(h.buckets, bucket*uintptr(t.bucketsize))) top := tophash(hash) search: for ; b != nil; b = b.overflow(t) { for i := uintptr(0); i < bucketCnt; i++ { if b.tophash[i] != top { continue } k := add(unsafe.Pointer(b), dataOffset+i*uintptr(t.keysize)) k2 := k if t.indirectkey { k2 = *((*unsafe.Pointer)(k2)) } if !alg.equal(key, k2) { continue } // 如果其中有指针,则仅清除键。 if t.indirectkey { *(*unsafe.Pointer)(k) = nil } else if t.key.kind&kindNoPointers == 0 { memclrHasPointers(k, t.key.size) } v := add(unsafe.Pointer(b), dataOffset+bucketCnt*uintptr(t.keysize)+i*uintptr(t.valuesize)) if t.indirectvalue { *(*unsafe.Pointer)(v) = nil } else if t.elem.kind&kindNoPointers == 0 { memclrHasPointers(v, t.elem.size) } else { memclrNoHeapPointers(v, t.elem.size) } // 若找到把对应的tophash里面的打上空的标记 b.tophash[i] = empty h.count-- break search } } if h.flags&hashWriting == 0 { throw("concurrent map writes") } h.flags &^= hashWriting }
如果正在扩容,并且操作的bucket还没搬迁完,那么搬迁bucket。
找出对应的key,如果key、value是包含指针的那么会清理指针指向的内存,否则不会回收内存。
3.6 map的扩容
通过上面的过程我们知道了,插入、删除过程都会触发扩容,判断扩容的函数如下:
// overLoadFactor 判断放置在1 << B个存储桶中的计数项目是否超过loadFactor。 func overLoadFactor(count int, B uint8) bool { return count > bucketCnt && uintptr(count) > loadFactorNum*(bucketShift(B)/loadFactorDen) //return 元素个数>8 && count>bucket数量*6.5,其中loadFactorNum是常量13,loadFactorDen是常量2,所以是6.5,bucket数量不算overflow bucket. } // tooManyOverflowBuckets 判断noverflow存储桶对于1 << B存储桶的map是否过多。 // 请注意,大多数这些溢出桶必须稀疏使用。如果使用密集,则我们已经触发了常规map扩容。 func tooManyOverflowBuckets(noverflow uint16, B uint8) bool { // 如果阈值太低,我们会做多余的工作。如果阈值太高,则增大和缩小的映射可能会保留大量未使用的内存。 //“太多”意味着(大约)溢出桶与常规桶一样多。有关更多详细信息,请参见incrnoverflow。 if B > 15 { B = 15 } // 译器在这里看不到B <16;掩码B生成较短的移位码。 return noverflow >= uint16(1)<<(B&15) } { .... // 如果我们达到最大负载率或溢流桶过多,并且我们还没有处于成长的中间,就开始成长。 if !h.growing() && (overLoadFactor(h.count+1, h.B) || tooManyOverflowBuckets(h.noverflow, h.B)) { hashGrow(t, h) goto again // 扩大表格会使所有内容失效,so try again } //if (不是正在扩容 && (元素个数/bucket数超过某个值 || 太多overflow bucket)) { 进行扩容 //} .... }
每次map进行更新或者新增的时候,会先通过以上函数判断一下load factor。来决定是否扩容。如果需要扩容,那么第一步需要做的,就是对hash表进行扩容:
//仅对hash表进行扩容,这里不进行搬迁 func hashGrow(t *maptype, h *hmap) { // 如果达到负载系数,则增大尺寸。否则,溢出bucket过多,因此,保持相同数量的存储桶并横向“增长”。 bigger := uint8(1) if !overLoadFactor(h.count+1, h.B) { bigger = 0 h.flags |= sameSizeGrow } oldbuckets := h.buckets newbuckets, nextOverflow := makeBucketArray(t, h.B+bigger, nil) flags := h.flags &^ (iterator | oldIterator) if h.flags&iterator != 0 { flags |= oldIterator } // 提交增长(atomic wrt gc) h.B += bigger h.flags = flags h.oldbuckets = oldbuckets h.buckets = newbuckets h.nevacuate = 0 h.noverflow = 0 if h.extra != nil && h.extra.overflow != nil { // 将当前的溢出bucket提升到老一代。 if h.extra.oldoverflow != nil { throw("oldoverflow is not nil") } h.extra.oldoverflow = h.extra.overflow h.extra.overflow = nil } if nextOverflow != nil { if h.extra == nil { h.extra = new(mapextra) } h.extra.nextOverflow = nextOverflow } //哈希表数据的实际复制是增量完成的,通过growWork()和evacuate()。 }
如果之前为2^n ,那么下一次扩容是2^(n+1),每次扩容都是之前的两倍。扩容后需要重新计算每一项在hash中的位置,新表为老的两倍,此时前文的oldbacket用上了,用来存同时存在的两个新旧map,等数据迁移完毕就可以释放oldbacket了。扩容的函数hashGrow其实仅仅是进行一些空间分配,字段的初始化,实际的搬迁操作是在growWork函数中:
func growWork(t *maptype, h *hmap, bucket uintptr) { //确保我们迁移了了对应的oldbucket,到我们将要使用的存储桶。 evacuate(t, h, bucket&h.oldbucketmask()) // 疏散一个旧桶以在生长上取得进展 if h.growing() { evacuate(t, h, h.nevacuate) } }
evacuate是进行具体搬迁某个bucket的函数,可以看出growWork会搬迁两个bucket,一个是入参bucket;另一个是h.nevacuate。这个nevacuate是一个顺序累加的值。可以想想如果每次仅仅搬迁进行写操作(赋值/删除)的bucket,那么有可能某些bucket就是一直没有机会访问到,那么扩容就一直没法完成,总是在扩容中的状态,因此会额外进行一次顺序迁移,理论上,有N个old bucket,最多N次写操作,那么必定会搬迁完。在advanceEvacuationMark中进行nevacuate的累加,遇到已经迁移的bucket会继续累加,一次最多加1024。
优点:均摊扩容时间,一定程度上缩短了扩容时间(和gc的引用计数法类似,都是均摊)overLoadFactor函数中有一个常量6.5(loadFactorNum/loadFactorDen)来进行影响扩容时机。这个值的来源是测试取中的结果。
4. map的并发安全性
map的并发操作不是安全的。并发起两个goroutine,分别对map进行数据的增加:
func main() { test := map[int]int {1:1} go func() { i := 0 for i < 10000 { test[1]=1 i++ } }() go func() { i := 0 for i < 10000 { test[1]=1 i++ } }() time.Sleep(2*time.Second) fmt.Println(test) } //fatal error: concurrent map read and map write
并发读写map结构的数据引起了错误。
解决方案1:加锁
func main() { test := map[int]int {1:1} var s sync.RWMutex go func() { i := 0 for i < 10000 { s.Lock() test[1]=1 s.Unlock() i++ } }() go func() { i := 0 for i < 10000 { s.Lock() test[1]=1 s.Unlock() i++ } }() time.Sleep(2*time.Second) fmt.Println(test) }
特点:实现简单粗暴,好理解。但是锁的粒度为整个map,存在优化空间。适用场景:all。
解决方案2:sync.Map
func main() { test := sync.Map{} test.Store(1, 1) go func() { i := 0 for i < 10000 { test.Store(1, 1) i++ } }() go func() { i := 0 for i < 10000 { test.Store(1, 1) i++ } }() time.Sleep(time.Second) fmt.Println(test.Load(1)) }
sync.Map的原理:sync.Map里头有两个map一个是专门用于读的read map,另一个是才是提供读写的dirty map;优先读read map,若不存在则加锁穿透读dirty map,同时记录一个未从read map读到的计数,当计数到达一定值,就将read map用dirty map进行覆盖。
特点:官方出品,通过空间换时间的方式,读写分离;不适用于大量写的场景,会导致read map读不到数据而进一步加锁读取,同时dirty map也会一直晋升为read map,整体性能较差。适用场景:大量读,少量写。
解决方案3:分段锁
这也是数据库常用的方法,分段锁每一个读写锁保护一段区间。sync.Map其实也是相当于表级锁,只不过多读写分了两个map,本质还是一样的。
优化方向:将锁的粒度尽可能降低来提高运行速度。思路:对一个大map进行hash,其内部是n个小map,根据key来来hash确定在具体的那个小map中,这样加锁的粒度就变成1/n了。例如
5. map的GC内存回收
golang里的map是只增不减的一种数组结构,他只会在删除的时候进行打标记说明该内存空间已经empty了,不会回收。
var intMap map[int]int func main() { printMemStats("初始化") // 添加1w个map值 intMap = make(map[int]int, 10000) for i := 0; i < 10000; i++ { intMap[i] = i } // 手动进行gc操作 runtime.GC() // 再次查看数据 printMemStats("增加map数据后") log.Println("删除前数组长度:", len(intMap)) for i := 0; i < 10000; i++ { delete(intMap, i) } log.Println("删除后数组长度:", len(intMap)) // 再次进行手动GC回收 runtime.GC() printMemStats("删除map数据后") // 设置为nil进行回收 intMap = nil runtime.GC() printMemStats("设置为nil后") } func printMemStats(mag string) { var m runtime.MemStats runtime.ReadMemStats(&m) log.Printf("%v:分配的内存 = %vKB, GC的次数 = %v\n", mag, m.Alloc/1024, m.NumGC) } //初始化:分配的内存 = 65KB, GC的次数 = 0 //增加map数据后:分配的内存 = 381KB, GC的次数 = 1 //删除前数组长度: 10000 //删除后数组长度: 0 //删除map数据后:分配的内存 = 381KB, GC的次数 = 2 //设置为nil后:分配的内存 = 68KB, GC的次数 = 3
可以看到delete是不会真正的把map释放的,所以要回收map还是需要设为nil
推荐:go语言教程
The above is the detailed content of Data structure in go-detailed explanation of dictionary map. For more information, please follow other related articles on the PHP Chinese website!