当前位置:网站首页>Golang--map扩容机制(含源码)
Golang--map扩容机制(含源码)
2022-07-02 06:11:00 【Srwici】
1 等量扩容
1.1 触发条件
溢出桶数量过多
- B大于15时,以15计算,如果溢出桶 >= 2^15次方,触发等量扩容
- 当B小于15时,以B计算,如果溢出桶 >= 大于2^B次方,触发等量扩容
1.2 触发结果
新建等量大小的map,将旧数据挪过去
1.3 源码
路径: go1.18/src/runtime/map.go
// overflow buckets 太多
func tooManyOverflowBuckets(noverflow uint16, B uint8) bool {
// If the threshold is too low, we do extraneous work.
// If the threshold is too high, maps that grow and shrink can hold on to lots of unused memory.
// "too many" means (approximately) as many overflow buckets as regular buckets.
// See incrnoverflow for more details.
if B > 15 {
B = 15
}
// The compiler doesn't see here that B < 16; mask B to generate shorter shift code.
return noverflow >= uint16(1)<<(B&15)
}
2 增量扩容
2.1 触发条件
承载因子>6.5
- 承载因子:map元素总量/bucket数量。
- map元素总量为:hmap中的count。
- bucket数量:2^B
2.2 触发结果
容量翻倍,挪移数据。
2.3 源码
路径: go1.18/src/runtime/map.go
func overLoadFactor(count int, B uint8) bool {
return count > bucketCnt && uintptr(count) > loadFactorNum*(bucketShift(B)/loadFactorDen)
//人话:当count大于8且承载因子大于6.5时可满足要求
}
count (
bucketCntBits = 3
bucketCnt = 1 << bucketCntBits
loadFactorNum = 13
loadFactorDen = 2
)
// bucketShift returns 1<<b, optimized for code generation.
// 翻译,返回2的B次方
func bucketShift(b uint8) uintptr {
// Masking the shift amount allows overflow checks to be elided.
return uintptr(1) << (b & (goarch.PtrSize*8 - 1))
}
边栏推荐
- From design delivery to development, easy and efficient!
- Comment utiliser mitmproxy
- 日期时间API详解
- Deep learning classification network -- alexnet
- ROS2----LifecycleNode生命周期节点总结
- 格式校验js
- Error creating bean with name 'instanceoperatorclientimpl' defined in URL when Nacos starts
- Use of Arduino wire Library
- Unity shader learning notes (3) URP rendering pipeline shaded PBR shader template (ASE optimized version)
- 注解和反射详解以及运用
猜你喜欢
ROS create workspace
Support new and old imperial CMS collection and warehousing tutorials
链表(线性结构)
Singleton mode compilation
复杂 json数据 js前台解析 详细步骤《案例:一》
浏览器原理思维导图
Contest3147 - game 38 of 2021 Freshmen's personal training match_ 1: Maximum palindromes
In depth understanding of JUC concurrency (II) concurrency theory
LeetCode 78. 子集
步骤详解 | 助您轻松提交 Google Play 数据安全表单
随机推荐
Data playback partner rviz+plotjuggler
Redis key value database [seckill]
栈(线性结构)
BGP报文详细解释
BGP中的状态机
The difference between session and cookies
Decryption skills of encrypted compressed files
VRRP之监视上行链路
LeetCode 39. 组合总和
[C language] simple implementation of mine sweeping game
Comment utiliser mitmproxy
Web page user step-by-step operation guide plug-in driver js
Common means of modeling: combination
复杂 json数据 js前台解析 详细步骤《案例:一》
492. Construction rectangle
Deep learning classification network -- alexnet
LeetCode 83. Delete duplicate elements in the sorting linked list
Verifying downloaded files using sha256 files
利用传统方法(N-gram,HMM等)、神经网络方法(CNN,LSTM等)和预训练方法(Bert等)的中文分词任务实现
ROS create workspace