2026-10-21 14:11:30 +08:00
<!DOCTYPE html>
< html lang = "zh-CN" data-theme = "light" >
< head >
< meta charset = "utf-8" >
< meta name = "viewport" content = "width=device-width, initial-scale=1" >
< title > 第 7 章 map: 从 hmap/bmap 到 1.24 Swiss Table · Go 八股知识库< / title >
< meta name = "description" content = "从哈希函数与冲突解法讲到 hmap/bmap 的读写路径、6.5 装载因子与渐进式扩容,再对比 1.24 Swiss Table 与并发安全的三种方案。" >
< link rel = "stylesheet" href = "assets/doc.css" >
< / head >
< body >
< header class = "topbar" >
< div class = "tb-in" >
< a class = "brand" href = "index.html" > < span class = "logo" > GO< / span > < div > Go 八股< small > 从运行时原理到面试表达< / small > < / div > < / a >
< div class = "crumbs" >
< a href = "index.html" > 总目录< / a > < span class = "sep" > /< / span > < b > 第 7 章< / b >
< / div >
< div class = "spacer" > < / div >
< button class = "btn" id = "tocToggle" > ☰ 导航< / button >
< button class = "btn" id = "themeBtn" title = "切换到深色主题" > 深色< / button >
< / div >
< / header >
< div class = "layout" id = "layout" >
< aside class = "sidebar" >
< h2 > 章节目录< / h2 >
< nav id = "chapters" > < a class = "toc-a" href = "01-goroutine.html" > < i class = "cn" > 1< / i > 从进程到 goroutine: 并发模型的底层账本< / a > < a class = "toc-a" href = "02-gmp.html" > < i class = "cn" > 2< / i > GMP 调度器: Go 如何把十万个 goroutine 跑起来< / a > < a class = "toc-a" href = "03-memory.html" > < i class = "cn" > 3< / i > 内存分配:从 mspan 到 mallocgc< / a > < a class = "toc-a" href = "04-gc-mark.html" > < i class = "cn" > 4< / i > 垃圾回收(上):三色标记与写屏障< / a > < a class = "toc-a" href = "05-gc-source.html" > < i class = "cn" > 5< / i > 垃圾回收(下):一次 GC 的完整生命周期< / a > < a class = "toc-a" href = "06-slice.html" > < i class = "cn" > 6< / i > slice: 视图、扩容与共享底层数组< / a > < span class = "toc-a active" aria-current = "page" > < i class = "cn" > 7< / i > map: 从 hmap/bmap 到 1.24 Swiss Table< / span > < div class = "subnav current" > < a class = "toc-a lv3" href = "#sec-7-1" > 7.1 哈希表基础:哈希函数、冲突与负载因子< / a > < a class = "toc-a lv3" href = "#sec-7-2" > 7.2 1.23 及以前: hmap 与 bmap< / a > < a class = "toc-a lv3" href = "#sec-7-3" > 7.3 读路径:从 hash 到 tophash< / a > < a class = "toc-a lv3" href = "#sec-7-4" > 7.4 写路径与扩容触发条件< / a > < a class = "toc-a lv3" href = "#sec-7-5" > 7.5 渐进式扩容: evacuate 怎么做< / a > < a class = "toc-a lv3" href = "#sec-7-6" > 7.6 遍历为什么是无序的< / a > < a class = "toc-a lv3" href = "#sec-7-7" > 7.7 Go 1.24 的 Swiss Table< / a > < a class = "toc-a lv3" href = "#sec-7-8" > 7.8 map 并发安全吗?三种方案< / a > < a class = "toc-a lv3" href = "#sec-7-9" > 7.9 sync.Map 与 map 的区别< / a > < a class = "toc-a lv3" href = "#sec-7-10" > 7.10 哈希攻击与随机种子< / a > < / div > < a class = "toc-a" href = "08-channel.html" > < i class = "cn" > 8< / i > channel: CSP 的载体与并发编排< / a > < a class = "toc-a" href = "09-defer.html" > < i class = "cn" > 9< / i > defer、panic、recover 与闭包< / a > < a class = "toc-a" href = "10-sync.html" > < i class = "cn" > 10< / i > 锁与同步原语:从 Mutex 到 singleflight< / a > < a class = "toc-a" href = "11-context.html" > < i class = "cn" > 11< / i > context: 取消、超时与 goroutine 泄露防治< / a > < a class = "toc-a" href = "12-interface.html" > < i class = "cn" > 12< / i > 接口:隐式契约与运行时表示< / a > < a class = "toc-a" href = "13-puzzles.html" > < i class = "cn" > 13< / i > 并发编程题:从交替打印到 worker pool< / a > < a class = "toc-a" href = "14-interview.html" > < i class = "cn" > 14< / i > 面试速查:对比、版本演进与高频追问< / a > < / nav >
< div class = "side-foot" >
< a class = "btn" href = "index.html" > ← 总目录< / a >
< / div >
< / aside >
< div class = "mask" id = "mask" > < / div >
< main class = "main-col" >
< article >
< p class = "chapnav" >
< a href = "index.html" > Go 八股< / a >
< span > ·< / span >
< span > 第 < b class = "pos" > 7< / b > / 14 章< / span >
< / p >
< h2 id = "ch7" > < span class = "n" > 7< / span > map: 从 hmap/bmap 到 1.24 Swiss Table< / h2 >
2026-10-22 23:35:36 +08:00
< div class = "box ok" >
< span class = "bt" > 面试直答 · 30 秒版< / span >
2026-10-25 17:16:48 +08:00
< p > < b > 问:< / b > Go 的 map 底层怎么实现, 1.24 到底改了什么?< / p >
< p > < b > 答:< / b > 1.23 及以前是桶数组加溢出链:哈希低位选桶、高 8 位做过滤,装载因子过 6.5 就翻倍扩容。1.24 起换成 Swiss Table: 控制字与键值分开存, 一次比较 8 个槽位。对外结论两代都一样——平均常数时间、遍历无序、并发写致命错误。< / p >
2026-10-22 23:35:36 +08:00
< ul >
2026-10-25 17:16:48 +08:00
< li > 遍历顺序每次都不同,这是故意的,别拿它当稳定顺序。< / li >
< li > 键必须可比较, slice、map、func 都不能当键。< / li >
< li > 并发写不是 panic, recover 不住,只能靠锁或分片。< / li >
2026-10-22 23:35:36 +08:00
< / ul >
< / div >
2026-10-21 14:11:30 +08:00
< div class = "lead" >
2026-10-25 17:16:48 +08:00
< b > 这一章解决什么:< / b > 「map 底层怎么实现」是区分度最高的一题,只答「哈希表,常数时间」一定被追穿。
这一章按< strong > 一次读、一次写、一次扩容< / strong > 拆开旧实现,再讲清换 Swiss Table 之后哪些结论还成立。
读完要能解释:装载因子为什么是 6.5、扩容为什么不能一次搬完、遍历顺序为什么每次不同、
并发写为什么是致命错误而不是 panic。
< / div >
< h4 > 读之前:七个词,两套术语< / h4 >
< div class = "tablewrap" >
< table >
< thead > < tr > < th > 词< / th > < th > 一句话< / th > < th > 属于哪一代 / 在哪节< / th > < / tr > < / thead >
< tbody >
< tr > < td > 桶( bmap) < / td > < td > 8 个键值槽位加 8 个哈希高位字节,定位与扩容的最小单位< / td > < td > 旧实现 · 7.2< / td > < / tr >
< tr > < td > 溢出桶< / td > < td > 桶装满了另挂的一只桶,用指针串成链< / td > < td > 旧实现 · 7.2< / td > < / tr >
< tr > < td > tophash< / td > < td > 哈希的高 8 位,先比它、再比完整键< / td > < td > 旧实现 · 7.3< / td > < / tr >
2026-11-03 21:17:47 +08:00
< tr > < td > 装载因子< / td > < td > 元素数 ÷ 桶数;旧实现阈值 6.5,新实现每组 7/8< / td > < td > 两代都有 · 7.1< / td > < / tr >
2026-10-25 17:16:48 +08:00
< tr > < td > 组( group) < / td > < td > 新实现里等价于桶的 8 槽单位< / td > < td > 新实现 · 7.7< / td > < / tr >
< tr > < td > 控制字< / td > < td > 每组 8 个字节,一字节记一个槽位的状态与哈希片段< / td > < td > 新实现 · 7.7< / td > < / tr >
< tr > < td > H1 / H2< / td > < td > 哈希切两段: H1 选组, H2 在组内筛槽< / td > < td > 新实现 · 7.7< / td > < / tr >
< / tbody >
< / table >
< / div >
< div class = "box tip" >
< span class = "bt" > 怎么读这一章< / span >
< p > 每节都是「现象 → 机制 → 代价 → 一句话」。现象段都能自己跑出来,先看它;标了 < span class = "tag s" > 可跳过< / span > 的段落第一遍直接跳过,不影响主线;每节最后加粗的那句是要背的。< / p >
< p > 三张图是全章骨架:前两张画的是旧实现,第三张画的是 1.24 起的新实现。< b > 看图前先确认自己在哪一代< / b > ,两套术语别混着记。< / p >
2026-10-21 14:11:30 +08:00
< / div >
< h3 id = "sec-7-1" > 7.1 哈希表基础:哈希函数、冲突与负载因子< / h3 >
2026-10-25 17:16:48 +08:00
< p > < span class = "tag" > 现象< / span > 往空 map 里连续塞整数,盯住堆内存:它会在元素个数为 9、14、27、53、105 时各阶跃一次, 每次大约是上一次的两倍。14 之后基本每次翻倍,而且< b > 从 14 起这些数字正好是「桶数 × 6.5 再加一」< / b > 。< / p >
< p > < span class = "tag" > 机制< / span > 哈希表把键压成一个整数,再用低位选桶,平均一步到位。但输出空间远小于输入空间,冲突必然发生,所以设计只剩两个决定:哈希够不够散,撞了往哪儿放。< / p >
< p > < b > 开放寻址< / b > 把所有元素放在一片连续数组里,撞了就按探测序列找下一个空槽。没有指针跳转、缓存友好,代价是删除只能留「墓碑」,而且对装载因子极敏感:占用超过七成,探测长度就飞涨。< / p >
< p > < b > 拉链法< / b > 在每个桶上挂一条链,装载因子可以大于一、删除就是摘链;代价是节点单独分配,一次查找要跳好几次指针,每个节点还多一份指针开销。< / p >
2026-10-21 14:11:30 +08:00
< div class = "tablewrap" >
< table >
< thead > < tr > < th > 维度< / th > < th > 开放寻址< / th > < th > 拉链法< / th > < / tr > < / thead >
< tbody >
< tr > < td > 布局< / td > < td > 一个数组,元素内联< / td > < td > 桶数组 + 链表/树节点< / td > < / tr >
< tr > < td > 缓存局部性< / td > < td > 好< / td > < td > 差(指针跳转)< / td > < / tr >
< tr > < td > 删除< / td > < td > 需要墓碑< / td > < td > 直接摘链< / td > < / tr >
< tr > < td > 装载因子< / td > < td > 通常 ≤ 0.7< / td > < td > 可大于 1< / td > < / tr >
< tr > < td > 最坏查找< / td > < td > O(n)< / td > < td > O(n),树化后 O(log n)< / td > < / tr >
< tr > < td > 代表< / td > < td > Python dict、Go 1.24< / td > < td > Java HashMap、Go 1.23< / td > < / tr >
< / tbody >
< / table >
< / div >
2026-10-25 17:16:48 +08:00
< p > Go 1.23 及以前不是纯的任一种,而是< b > 混合体< / b > :桶数组连续、桶内 8 槽线性扫、桶之间用溢出桶指针串链,既占了局部性又躲开墓碑,代价是每桶多一个溢出指针。< / p >
< p > 为什么阈值是 < b > 6.5< / b > 而不是 8? 元素落桶近似泊松分布, 平均每桶 8 个时必然有桶超标、要挂溢出链,多一次指针跳转和一次缓存未命中。压到 6.5,绝大多数桶都装得下,再低就是白占内存。< / p >
2026-10-21 14:11:30 +08:00
< div class = "box note" >
2026-10-25 17:16:48 +08:00
< span class = "bt" > 两种装载因子的分母不一样< / span >
< p > Go 的 6.5 是「元素数 ÷ 桶数」; Java、Python 常说的 0.75 是「元素数 ÷ 槽位数」。6.5 除以每桶 8 槽约等于 0.81, < b > Go 的阈值其实更激进< / b > ,靠桶内 8 槽加溢出链兜底。< / p >
2026-10-21 14:11:30 +08:00
< / div >
2026-10-25 17:16:48 +08:00
< p > < span class = "tag" > 代价< / span > 混合体把两种方案的账单都留了一点:桶内 8 槽是为了摊销溢出链,浪费的是「没装满也要占一整个桶」;溢出链救的是极端情况,代价是扩容判定要多看一个溢出桶计数。< / p >
< p class = "take" > < b > 一句话:< / b > 哈希表只做两个决定——哈希够不够散、撞了往哪放; Go 的 6.5 是元素数除以桶数,分母不是槽位。< / p >
2026-10-21 14:11:30 +08:00
< h3 id = "sec-7-2" > 7.2 1.23 及以前: hmap 与 bmap< / h3 >
2026-10-25 17:16:48 +08:00
< p > < span class = "tag" > 现象< / span > 打印 map 变量的尺寸,只有 < b > 8< / b > 字节——它就是一个指针。对应地:把 map 传进函数,函数里加元素外面看得见;而声明后没初始化的 map, 读它很安全, 写它直接 panic。< / p >
< p > < span class = "tag" > 机制< / span > 八个字节指向运行时里的 < code > hmap< / code > , 所以「引用类型」只是表象, 被复制的就是这根指针。hmap 字段不多,但每个都分工明确:< / p >
2026-10-21 14:11:30 +08:00
< pre data-lang = "go" data-name = "runtime/map.go( Go 1.23,简化)" > type hmap struct {
count int // 元素个数, len(m) 直接读它, O(1)
flags uint8 // 状态位: hashWriting / iterator / sameSizeGrow ...
B uint8 // 桶数组长度是 2^B
noverflow uint16 // 溢出桶的近似数量,用于判定等量扩容
hash0 uint32 // 哈希种子,创建 map 时随机生成
buckets unsafe.Pointer // 指向 2^B 个桶的一整片连续内存
oldbuckets unsafe.Pointer // 扩容期间指向旧桶,大小是新桶的一半
2026-10-21 15:21:43 +08:00
nevacuate uintptr // 搬迁进度:下标小于它的旧桶都已搬完
2026-10-21 14:11:30 +08:00
extra *mapextra // 溢出桶指针缓存,小 map 时为 nil
}
type mapextra struct {
overflow *[]*bmap // 正在使用的溢出桶
oldoverflow *[]*bmap // 旧桶的溢出桶,扩容期间要保住不被 GC
nextOverflow *bmap // 下一个可用的预分配溢出桶
}< / pre >
2026-10-25 17:16:48 +08:00
< p > < code > B< / code > 是钥匙:桶数恒为 2 的幂,所以只存指数,选桶用掩码与哈希相与,比取模快。扩容也必须翻倍——只有 2 的幂,位与才等价于取模,多出的那位哈希决定元素去哪个新桶。< / p >
2026-10-21 14:11:30 +08:00
< p > 桶 < code > bmap< / code > 的设计更绕,源码里它只声明了一个 < code > tophash< / code > 数组:< / p >
< pre data-lang = "go" data-name = "runtime/map.go: bmap 的声明与真实布局" > // 源码里的声明:只有一个 tophash 数组
type bmap struct {
tophash [bucketCnt]uint8 // bucketCnt = 8, 存 key 哈希的高 8 位
}
// 编译器( cmd/compile) 按 key/elem 类型生成的真实布局:
// keys、values、overflow 都靠 dataOffset 加偏移算出来,所以源码里看不见
type bmap struct {
topbits [8]uint8 // 8 个槽位的哈希高 8 位
keys [8]keytype // 先连续放 8 个 key
values [8]valuetype // 再连续放 8 个 value
pad uintptr
overflow uintptr // 指向下一个溢出桶
}< / pre >
2026-10-25 17:16:48 +08:00
< p > 键和值为什么不交错放?为了对齐。小整数配 64 位整数时, 交错排每槽要多凑七个字节, 8 个槽白扔五十多个字节;分区存几乎不浪费,元素上百万就能省出几十兆。< / p >
< figure class = "figure" >
< svg viewBox = "0 0 720 460" role = "img" aria-label = "旧实现的结构: map 变量指向 hmap, hmap 指向一片连续的桶数组,每个桶内依次是 8 个 tophash、8 个键、8 个值和末尾的 overflow 指针,装不下时 overflow 指针指向下一个桶,串成链" >
< defs >
< marker id = "ar7a" viewBox = "0 0 10 10" refX = "9" refY = "5" markerWidth = "7" markerHeight = "7" orient = "auto-start-reverse" >
< path d = "M0,0 L10,5 L0,10 z" fill = "var(--muted)" / >
< / marker >
< / defs >
< text x = "206" y = "50" font-size = "12" fill = "var(--muted)" text-anchor = "start" > 2^B 个桶,一整片连续内存< / text >
< rect x = "20" y = "40" width = "150" height = "120" rx = "8" fill = "var(--brand-soft)" stroke = "var(--brand)" / >
< text x = "95" y = "66" text-anchor = "middle" font-size = "13" fill = "var(--brand-ink)" > hmap< / text >
< text x = "95" y = "90" text-anchor = "middle" font-size = "11" fill = "var(--ink)" > count / B / hash0< / text >
< text x = "95" y = "112" text-anchor = "middle" font-size = "11" fill = "var(--ink)" > buckets< / text >
< text x = "95" y = "134" text-anchor = "middle" font-size = "11" fill = "var(--ink)" > oldbuckets< / text >
< text x = "95" y = "152" text-anchor = "middle" font-size = "11" fill = "var(--ink)" > nevacuate< / text >
< line x1 = "170" y1 = "108" x2 = "204" y2 = "108" stroke = "var(--muted)" marker-end = "url(#ar7a)" / >
< rect x = "206" y = "60" width = "360" height = "90" rx = "8" fill = "none" stroke = "var(--line)" stroke-dasharray = "4 4" / >
< rect x = "216" y = "84" width = "104" height = "52" rx = "6" fill = "var(--card)" stroke = "var(--line)" / >
< text x = "268" y = "114" text-anchor = "middle" font-size = "12" fill = "var(--ink)" > 桶 0< / text >
< rect x = "334" y = "84" width = "104" height = "52" rx = "6" fill = "var(--card)" stroke = "var(--line)" / >
< text x = "386" y = "114" text-anchor = "middle" font-size = "12" fill = "var(--ink)" > 桶 1< / text >
< rect x = "452" y = "84" width = "104" height = "52" rx = "6" fill = "var(--card)" stroke = "var(--line)" / >
< text x = "504" y = "114" text-anchor = "middle" font-size = "12" fill = "var(--ink)" > 桶 2^B-1< / text >
< line x1 = "268" y1 = "150" x2 = "268" y2 = "196" stroke = "var(--muted)" marker-end = "url(#ar7a)" / >
< rect x = "150" y = "200" width = "460" height = "160" rx = "8" fill = "var(--card)" stroke = "var(--line)" / >
< text x = "380" y = "224" text-anchor = "middle" font-size = "13" fill = "var(--ink)" > 一个桶( bmap) < / text >
< rect x = "170" y = "234" width = "420" height = "26" rx = "4" fill = "var(--soft)" stroke = "var(--line)" / >
< text x = "380" y = "252" text-anchor = "middle" font-size = "12" fill = "var(--ink)" > tophash[8]:每个槽 1 字节,只存哈希高位< / text >
< rect x = "170" y = "266" width = "420" height = "26" rx = "4" fill = "var(--soft)" stroke = "var(--line)" / >
< text x = "380" y = "284" text-anchor = "middle" font-size = "12" fill = "var(--ink)" > keys[8]: 8 个键背靠背< / text >
< rect x = "170" y = "298" width = "420" height = "26" rx = "4" fill = "var(--soft)" stroke = "var(--line)" / >
< text x = "380" y = "316" text-anchor = "middle" font-size = "12" fill = "var(--ink)" > values[8]: 8 个值背靠背< / text >
< text x = "380" y = "342" text-anchor = "middle" font-size = "12" fill = "var(--muted)" > 末尾的 overflow 指针指向下一个桶< / text >
< line x1 = "380" y1 = "360" x2 = "380" y2 = "386" stroke = "var(--muted)" marker-end = "url(#ar7a)" / >
< rect x = "250" y = "390" width = "220" height = "56" rx = "8" fill = "var(--warn-bg)" stroke = "var(--warn)" / >
< text x = "360" y = "412" text-anchor = "middle" font-size = "12" fill = "var(--ink)" > 溢出桶(同样的结构)< / text >
< text x = "360" y = "432" text-anchor = "middle" font-size = "11" fill = "var(--muted)" > 还装不下就继续挂,成一条链< / text >
< / svg >
< div class = "figcap" > < b > 图 1< / b > · 旧实现: map 变量是个指针,指向 hmap; hmap 指向 2^B 个连续桶,桶里先放 8 个 tophash, 再放键、放值, 装不下就挂溢出桶。< / div >
< / figure >
2026-10-21 14:11:30 +08:00
< div class = "tablewrap" >
< table >
< thead > < tr > < th > 字段< / th > < th > 作用< / th > < th > 追问点< / th > < / tr > < / thead >
< tbody >
< tr > < td > < code > count< / code > < / td > < td > 元素个数< / td > < td > < code > len(m)< / code > 是 O(1),不遍历桶< / td > < / tr >
< tr > < td > < code > B< / code > < / td > < td > 桶数的对数< / td > < td > 桶数 = 2< sup > B< / sup > ,决定掩码位宽< / td > < / tr >
< tr > < td > < code > hash0< / code > < / td > < td > 哈希种子< / td > < td > 防哈希洪水攻击,见 7.10< / td > < / tr >
< tr > < td > < code > buckets< / code > < / td > < td > 当前桶数组< / td > < td > 可能同时存在 < code > oldbuckets< / code > < / td > < / tr >
< tr > < td > < code > oldbuckets< / code > < / td > < td > 扩容前的旧桶< / td > < td > 非 nil 就说明正在扩容< / td > < / tr >
2026-10-21 15:21:43 +08:00
< tr > < td > < code > nevacuate< / code > < / td > < td > 搬迁进度指针< / td > < td > 不是「搬了几个」的计数,而是「下一个待搬桶号」:[0, nevacuate) 已搬完,等于旧桶数即结束< / td > < / tr >
2026-10-21 14:11:30 +08:00
< tr > < td > < code > noverflow< / code > < / td > < td > 溢出桶计数< / td > < td > 用于判定等量扩容< / td > < / tr >
< / tbody >
< / table >
< / div >
2026-10-25 17:16:48 +08:00
< p > < span class = "tag s" > 可跳过< / span > 桶数取 2 的幂还有个好处:算桶数只要移位,不用除法;< code > B ≥ 4< / code > 时还会顺手多分配一批溢出桶,和正常桶放在同一片内存里,不够了才单独申请并累加计数。这部分对理解读写路径没有影响。< / p >
2026-11-03 21:17:47 +08:00
< p > < span class = "tag" > 代价< / span > 为了省一次指针跳转,每个桶都多存 8 个 tophash 字节;空 map 不预先挂桶,第一次写入才分配首个桶/组;但一组就是 8 个槽,元素很少的 map 也偏胖,这也是编译器把小 map 的首组放到栈上的动机。< / p >
2026-10-25 17:16:48 +08:00
< div class = "box warn" >
< span class = "bt" > 易错点 · 长度是现成的数字< / span >
< p > hmap 里有个计数字段,写一次加一、删一次减一,所以 < code > len(m)< / code > 是常数时间,< b > 不会去数桶< / b > 。验证:百万元素的 map 调 < code > len< / code > 只要几十纳秒,和空 map 一样快。扩容期间新旧桶都有元素,这个计数既没翻倍也没减半。< / p >
2026-10-21 14:11:30 +08:00
< / div >
2026-10-25 17:16:48 +08:00
< p class = "take" > < b > 一句话:< / b > map 变量只是一根指向 hmap 的指针,桶数存的是指数,长度是现成的计数。< / p >
2026-10-21 14:11:30 +08:00
< h3 id = "sec-7-3" > 7.3 读路径:从 hash 到 tophash< / h3 >
2026-10-25 17:16:48 +08:00
< p > < span class = "tag" > 现象< / span > 对一个 < code > map[int]int< / code > 取键,< code > go build -gcflags=-S< / code > 里能看到 < code > CALL runtime.mapaccess1_fast64< / code > ;把取值换成带 ok 的写法,名字变成 < code > mapaccess2_fast64< / code > 。也就是说,读一次 map 就是一次函数调用,语法糖下面全是运行时。< / p >
< p > < span class = "tag" > 机制< / span > 这个函数只做六件事:算哈希、低位选桶、把高 8 位当 tophash、逐个比 tophash、比完整键、沿溢出链继续找。找不到就返回一个全局零值的地址——所以读 nil map 不会崩。1.23 及以前的实现:< / p >
2026-10-21 15:21:43 +08:00
< pre data-lang = "go" data-name = "runtime/map.go: mapaccess1( Go 1.23 及以前,旧 hmap 实现)" > func mapaccess1(t *maptype, h *hmap, key unsafe.Pointer) unsafe.Pointer {
2026-10-21 14:11:30 +08:00
if h == nil || h.count == 0 {
return unsafe.Pointer(& zeroVal[0]) // nil map 读是安全的
}
hash := t.key.alg.hash(key, uintptr(h.hash0)) // 1. 带种子算哈希
m := bucketMask(h.B) // 2. 低 B 位掩码
b := (*bmap)(add(h.buckets, (hash& m)*uintptr(t.bucketsize)))
top := tophash(hash) // 3. 高 8 位
bucketloop:
for ; b != nil; b = b.overflow(t) { // 4. 沿溢出链走
for i := uintptr(0); i < bucketCnt; i++ {
if b.tophash[i] != top {
if b.tophash[i] == emptyRest {
break bucketloop // 后面全空,提前收工
}
continue
}
k := add(unsafe.Pointer(b), dataOffset+i*uintptr(t.keysize))
if t.key.alg.equal(key, k) { // 5. 真正比较 key
v := add(unsafe.Pointer(b),
dataOffset+bucketCnt*uintptr(t.keysize)+i*uintptr(t.valuesize))
return v
}
}
}
return unsafe.Pointer(& zeroVal[0]) // 6. 未命中返回零值
}< / pre >
2026-10-25 17:16:48 +08:00
< p > 片段里 < code > t.key.alg.hash< / code > 是 1.20 以前的字段名,后来改叫 < code > t.Hasher< / code > ;保留旧写法只为对齐「桶 + tophash」这套结构。1.24 起连结构都换了,真实查找在 < code > internal/runtime/maps< / code > ,见 7.7。< / p >
< p > 定位用< strong > 低位< / strong > 、过滤用< strong > 高 8 位< / strong > ,不是随便切的:若 tophash 也取低位,同桶 8 个元素的 tophash 高度相似,比较全部通过,全落到最贵的键比较上。取高 8 位等于用一个字节把候选从 8 个筛到一两个。< / p >
2026-11-03 21:17:47 +08:00
< p > tophash 里还藏着几个特殊值:< code > emptyRest< / code > 表示此槽及其后全空,可以直接跳出循环;< code > emptyOne< / code > 表示此槽空但后面还有;< code > evacuatedX/Y< / code > 是扩容期间「已搬走」的标记, 遇到它说明这个旧桶已经搬空、元素在新桶里( X 去新桶号 oldbucket, Y 去 oldbucket+2^B) , 得去新桶找; 只有旧桶还没搬过时才读旧桶。< / p >
2026-10-25 17:16:48 +08:00
< div class = "box note" >
< span class = "bt" > 为什么推荐 v, ok := m[k]< / span >
< p > 零值语义让「不存在」和「存在但值为零」无法区分:< code > map[string]*T< / code > 取到的 nil 可能没存过,也可能存了个 nil。只有带 ok 的写法(< code > mapaccess2< / code > 的第二个返回值)能区分。< / p >
2026-10-21 14:11:30 +08:00
< / div >
2026-10-25 17:16:48 +08:00
< p > < span class = "tag" > 代价< / span > 读的代价分两档: tophash 不匹配, 只是几个纳秒的字节比较; tophash 匹配后要比完整键,长字符串最坏要逐字节比到末尾,这是整条路径上最贵的一步。所以编译器给常见类型各生成一份快速路径。< / p >
< p class = "take" > < b > 一句话:< / b > 一次读是六步, tophash 只负责把 8 个候选筛成一两个,真正花时间的是完整键比较。< / p >
2026-10-21 14:11:30 +08:00
< h3 id = "sec-7-4" > 7.4 写路径与扩容触发条件< / h3 >
2026-10-25 17:16:48 +08:00
< p > < span class = "tag" > 现象< / span > 写 < code > m[k].X = 1< / code > ,编译不过:< code > cannot assign to struct field m[k].X in map< / code > ;写 < code > & m[k]< / code > 一样被拒:< code > cannot take address of m[k]< / code > 。map 的元素不能取地址,这是编译器硬拦下来的。< / p >
< p > < span class = "tag" > 机制< / span > 因为写入时桶可能正在搬家,元素随时会挪位置,存下来的地址立刻就是悬空的。所以 < code > mapassign< / code > 只返回 value 的地址,编译器紧跟一条赋值指令写到那个地址上——地址只在这一次赋值内有效。< / p >
2026-10-21 14:11:30 +08:00
< pre data-lang = "go" data-name = "runtime/map.go: mapassign 的关键片段( Go 1.23) " > func mapassign(t *maptype, h *hmap, key unsafe.Pointer) unsafe.Pointer {
...
hash := t.key.alg.hash(key, uintptr(h.hash0))
h.flags ^= hashWriting // 置位:告诉别人"我在写"
again:
bucket := hash & bucketMask(h.B)
if h.growing() {
growWork(t, h, bucket) // 顺手搬 1~ 2 个旧桶
}
// 两个扩容条件:装载因子 > 6.5,或者溢出桶太多
if !h.growing() & & (overLoadFactor(h.count+1, h.B) ||
tooManyOverflowBuckets(h.noverflow, h.B)) {
hashGrow(t, h) // 只分配新桶,不搬数据
goto again // 桶变了,重新定位
}
... // 找空槽 → 找不到就 newoverflow → 返回 value 地址
h.count++
h.flags & ^= hashWriting // 清除写标志
return val
}< / pre >
2026-10-25 17:16:48 +08:00
< p > 两个条件对应两种「不健康」:< strong > 装载因子过高< / strong > 是元素真多、平均负载超 6.5、查找要顺链走,于是桶数翻倍;< strong > 溢出桶过多< / strong > 是元素不多但桶被写碎了——反复增删后一个桶只剩 2 个有效元素却挂着 3 个溢出桶,此时桶数不变,只重排元素收紧链。< / p >
< p > 阈值细节:要求 < code > count > 8< / code > 且 < code > count > 6.5× 2^B< / code > (源码用整数 < code > 13/2< / code > 避免浮点);溢出桶阈值在 < code > B ≤ 15< / code > 时是 < code > 2^B< / code > ,更大就固定 < code > 2^15< / code > ——桶数很大后按比例算会频繁误触发,所以封顶。< / p >
2026-10-21 14:11:30 +08:00
< div class = "tablewrap" >
< table >
< thead > < tr > < th > 版本< / th > < th > 扩容条件< / th > < th > 扩容方式< / th > < / tr > < / thead >
< tbody >
< tr > < td > ≤ 1.23< / td > < td > 装载因子 > 6.5,或溢出桶 ≥ 2< sup > B< / sup > ( B> 15 时 2< sup > 15< / sup > ) < / td > < td > 翻倍扩容 / 等量扩容< / td > < / tr >
< tr > < td > ≥ 1.24< / td > < td > 单张 table 的已用槽位 + 墓碑超过容量阈值< / td > < td > 表内翻倍,或按哈希下一位 split 成两张表< / td > < / tr >
< / tbody >
< / table >
< / div >
2026-10-25 17:16:48 +08:00
< p > < span class = "tag" > 代价< / span > 写比读贵,贵在三处固定开销:先置写标志,再检查是否正在扩容、是就顺手搬桶,找不到空槽还得挂一个溢出桶。所以写密集的场景,批量插入前用 < code > make(map[K]V, n)< / code > 预留容量最划算,能省掉中间几轮扩容。< / p >
< div class = "box warn" >
< span class = "bt" > 易错点 · map 的元素不是变量< / span >
< p > 不能取地址,是因为元素可能被搬走,< b > 不是设计疏漏< / b > 。要改结构体字段,只能整体写回(< code > m[k] = 改了字段的副本< / code > ),或者一开始就存指针 < code > map[K]*T< / code > 。验证:< code > go vet< / code > 不报,但编译器直接拒绝这两种写法,报错文案就是现象段那两句。< / p >
2026-10-21 14:11:30 +08:00
< / div >
2026-10-25 17:16:48 +08:00
< p class = "take" > < b > 一句话:< / b > mapassign 只交出一个临时地址,元素不是变量;扩容要么翻倍、要么原地收紧溢出链。< / p >
2026-10-21 14:11:30 +08:00
< h3 id = "sec-7-5" > 7.5 渐进式扩容: evacuate 怎么做< / h3 >
2026-10-25 17:16:48 +08:00
< p > < span class = "tag" > 现象< / span > 在扩容刚触发的一瞬间打个断点:新桶数组已经分配好,< code > oldbuckets< / code > 还指着旧数组,< code > nevacuate< / code > 还是 0——一个元素都没搬。可这时候去读 map, 任何键都能读到, 一次都不缺。< / p >
< p > < span class = "tag" > 机制< / span > 因为 < code > hashGrow< / code > < b > 只分配、不搬迁< / b > :申请新桶、把旧桶挂到 < code > oldbuckets< / code > 、进度清零,立刻返回。搬数据摊到后面的每次写和删里,由 < code > growWork< / code > 一次搬一两个桶。< / p >
2026-10-21 14:11:30 +08:00
< pre data-lang = "go" data-name = "runtime/map.go: evacuate 的分流逻辑( Go 1.23) " > func evacuate(t *maptype, h *hmap, oldbucket uintptr) {
b := (*bmap)(add(h.oldbuckets, oldbucket*uintptr(t.bucketsize)))
if evacuated(b) {
return // 已经搬过了
}
newbit := h.noldbuckets() // 旧桶数量,也就是新增的那一位
x := & xy[0] // 目标 1: 新桶号 = oldbucket
y := & xy[1] // 目标 2: 新桶号 = oldbucket + newbit
for ; b != nil; b = b.overflow(t) {
for i := uintptr(0); i < bucketCnt; i++ {
k := add(unsafe.Pointer(b), dataOffset+i*uintptr(t.keysize))
v := add(k, bucketCnt*uintptr(t.keysize))
hash := t.key.alg.hash(k, uintptr(h.hash0))
var useY uint8
if hash& newbit != 0 { // 新多出来的那一位是 1 → 去 y
useY = 1
}
dst := & xy[useY]
dst.b.tophash[dst.i& (bucketCnt-1)] = b.tophash[i]
typedmemmove(t.key, dst.k, k)
typedmemmove(t.elem, dst.v, v)
b.tophash[i] = evacuatedX + useY // 打上"已搬迁"标记
}
}
}< / pre >
2026-10-25 17:16:48 +08:00
< p > 分流规则很简单:桶数从 2< sup > B< / sup > 变成 2< sup > B+1< / sup > ,掩码多一位,元素归属只看哈希的第 B 位——0 去原桶号, 1 去原桶号加 2< sup > B< / sup > 。所以< b > 一个旧桶最多裂成两个新桶< / b > ,绝不跑到别处,这也是并发推进的前提:每个旧桶的归属由它自己决定。< / p >
< figure class = "figure" >
< svg viewBox = "0 0 720 350" role = "img" aria-label = "扩容分流:一个旧桶里的元素按哈希新增的第 B 位分成两组, 0 进入原桶号对应的新桶, 1 进入原桶号加 2 的 B 次方的新桶,一个旧桶最多裂成两个" >
< defs >
< marker id = "ar7b" viewBox = "0 0 10 10" refX = "9" refY = "5" markerWidth = "7" markerHeight = "7" orient = "auto-start-reverse" >
< path d = "M0,0 L10,5 L0,10 z" fill = "var(--muted)" / >
< / marker >
< / defs >
< text x = "360" y = "40" text-anchor = "middle" font-size = "13" fill = "var(--ink)" > 同一个哈希:低 B 位选旧桶,第 B 位选新表的那一半< / text >
< rect x = "40" y = "120" width = "190" height = "100" rx = "8" fill = "var(--brand-soft)" stroke = "var(--brand)" / >
< text x = "135" y = "158" text-anchor = "middle" font-size = "13" fill = "var(--brand-ink)" > 旧桶 i< / text >
< text x = "135" y = "184" text-anchor = "middle" font-size = "11" fill = "var(--ink)" > 8 个槽混在一起< / text >
< rect x = "430" y = "50" width = "230" height = "90" rx = "8" fill = "var(--card)" stroke = "var(--line)" / >
< text x = "545" y = "85" text-anchor = "middle" font-size = "13" fill = "var(--ink)" > 新桶 i< / text >
< text x = "545" y = "110" text-anchor = "middle" font-size = "11" fill = "var(--muted)" > 第 B 位 = 0< / text >
< rect x = "430" y = "210" width = "230" height = "90" rx = "8" fill = "var(--card)" stroke = "var(--line)" / >
< text x = "545" y = "245" text-anchor = "middle" font-size = "13" fill = "var(--ink)" > 新桶 i + 2^B< / text >
< text x = "545" y = "270" text-anchor = "middle" font-size = "11" fill = "var(--muted)" > 第 B 位 = 1< / text >
< path d = "M230,152 C320,142 340,102 424,96" fill = "none" stroke = "var(--muted)" marker-end = "url(#ar7b)" / >
< path d = "M230,190 C320,200 340,250 424,256" fill = "none" stroke = "var(--muted)" marker-end = "url(#ar7b)" / >
< text x = "360" y = "336" text-anchor = "middle" font-size = "11" fill = "var(--muted)" > 一个旧桶最多裂成两个,绝不会跑到第三个桶< / text >
< / svg >
< div class = "figcap" > < b > 图 2< / b > · 扩容分流:桶数翻倍只多一位掩码,每个旧桶按这一位把元素分到两个新桶。< / div >
< / figure >
< p > 等量扩容是 1:1 映射,只用到一个目标桶。它不腾空间,只< b > 整理< / b > :把散在溢出链上的元素装回正常桶,让 GC 回收旧溢出桶。典型场景是高频增删的缓存——元素不多、溢出桶一路涨,看着像内存泄漏,其实是桶被写碎了。< / p >
< p > < span class = "tag s" > 可跳过< / span > 进度记在 < code > nevacuate< / code > 里:每搬完一个桶就加一,还会连跳过一串已搬过的桶(最多 1024 个,防止一次占用太久);等于旧桶数时,把 < code > oldbuckets< / code > 置 nil, GC 就能回收旧数组。< / p >
2026-10-21 14:11:30 +08:00
< div class = "box note" >
2026-10-25 17:16:48 +08:00
< span class = "bt" > 为什么一次搬 1~ 2 个桶,不是固定 1 个< / span >
< p > < code > growWork< / code > 干两件事:先搬「这次写操作要用的那个桶」,保证本次读写看到正确数据;再搬进度指针指向的下一个桶,保证推进不停。只搬第一个的话,写入集中在少数桶上时,扩容可能永远推不完。< / p >
2026-10-21 14:11:30 +08:00
< / div >
2026-10-25 17:16:48 +08:00
< p > < span class = "tag" > 代价< / span > 峰值内存接近翻倍,每次读写都多一次「旧桶是否为空」的判断;命中旧桶还得再定位一次。这是拿持续的小开销和峰值内存,换没有大卡顿。< / p >
< div class = "box warn" >
2026-11-03 21:17:47 +08:00
< span class = "bt" > 易错点 · 扩容期间的读只查一处< / span >
< p > 读的时候先看 < code > oldbuckets< / code > 是不是 nil; 不是就看目标旧桶搬没搬过: 没搬就只读旧桶( 元素还在这儿) , 搬完了就只读新桶。< b > 一次读只碰一套数组< / b > ,不会读到两份。验证:在 < code > evacuate< / code > 里打断点,能看到 < code > nevacuate< / code > 缓慢增加而读一直正常。< / p >
2026-10-25 17:16:48 +08:00
< / div >
2026-11-03 21:17:47 +08:00
< p class = "take" > < b > 一句话:< / b > 扩容只分配不搬迁,读写时顺手搬一两个桶,翻倍扩容时一个旧桶只裂成两个新桶。< / p >
2026-10-21 14:11:30 +08:00
< h3 id = "sec-7-6" > 7.6 遍历为什么是无序的< / h3 >
2026-10-25 17:16:48 +08:00
< p > < span class = "tag" > 现象< / span > 在同一个进程里对同一个 map 连跑三次 < code > for k := range m< / code > ,三次打印出的键序列都不一样;元素上百个之后,看起来就是完全随机的排列。< / p >
< p > < span class = "tag" > 机制< / span > 因为遍历的起点是随机的:开始遍历时取一个随机数,低 B 位选起始桶,接下来 3 位选桶内偏移,然后从那里绕一整圈回来。< / p >
2026-10-21 14:11:30 +08:00
< pre data-lang = "go" data-name = "runtime/map.go: mapiterinit 的随机起点( Go 1.23) " > func mapiterinit(t *maptype, h *hmap, it *hiter) {
...
r := uintptr(fastrand())
if h.B > 31-bucketCntBits {
r += uintptr(fastrand()) < < 31 // 桶数很大时多取一次随机数
}
it.startBucket = r & bucketMask(h.B) // 随机起始桶
it.offset = uint8(r > > h.B & (bucketCnt - 1)) // 随机桶内偏移
it.bucket = it.startBucket
it.wrapped = false
...
}< / pre >
2026-10-25 17:16:48 +08:00
< p > 为什么故意随机?因为顺序本来就不稳定:扩容途中 key 会被搬走,删除留下的空槽会被复用,桶和溢出链之间也没有先后。如果运行时保证了顺序,一定有人写出依赖顺序的代码,再在某次扩容后悄悄变行为——不如让它在开发阶段就随机失败。< / p >
2026-10-21 14:11:30 +08:00
< div class = "box warn" >
2026-10-25 17:16:48 +08:00
< span class = "bt" > 易错点 · 遍历顺序是真随机,不是打乱一下< / span >
< p > 起始桶随机、桶内偏移也随机,同一个键可能在一次遍历里排最前、下一次排最后。更要紧的是规范只保证一条:遍历过程中被删掉、且还没遍历到的元素不会再产出。至于每个元素会不会出现两次、遍历期间新插入的会不会出现,< b > 都不保证< / b > 。< / p >
2026-10-21 14:11:30 +08:00
< / div >
2026-10-25 17:16:48 +08:00
< p > < span class = "tag s" > 可跳过< / span > 遍历途中遇到扩容最绕:旧实现快照 B, 发现 B 变了就回头读旧桶, 只交出「按新掩码也属于当前桶」的元素, 尽量不漏不重; Swiss 版用 < code > clearSeq< / code > 与 < code > grownKeyElem< / code > 兜底,键「不等于自己」(比如 NaN) 时直接从旧组交出。规范只说「未到达且被删的不再产出」, 就是给这些细节留余地。< / p >
< p > < span class = "tag" > 代价< / span > 顺序这件事彻底交给调用方:要稳定输出就自己收集键排序,多花一个 O(n log n);迭代器本身还要保存起始桶、偏移、当前桶指针等一堆状态,遍历比普通数组循环贵。< / p >
< p class = "take" > < b > 一句话:< / b > 起点桶和桶内偏移都随机,所以顺序是真随机;要稳定输出,自己排序。< / p >
2026-10-21 14:11:30 +08:00
< h3 id = "sec-7-7" > 7.7 Go 1.24 的 Swiss Table< / h3 >
2026-10-25 17:16:48 +08:00
< p > < span class = "tag" > 现象< / span > 在 1.25 上编译两次:默认构建,再用 < code > GOEXPERIMENT=noswissmap< / code > 构建一次。两次 < code > go tool objdump< / code > 出来的读写函数不一样——默认走 < code > internal/runtime/maps< / code > ,加了开关又回到旧的 hmap 路径。同一份源码两套实现,这是 1.24 之后才有的状态。< / p >
< p > < span class = "tag" > 机制< / span > 版本因此分三代: 1.23 及以前只有 hmap/bmap; 1.24、1.25 默认 Swiss、旧实现可选; 1.26 删掉 < code > runtime/map_noswiss.go< / code > ,只剩 Swiss。< / p >
2026-11-03 21:17:47 +08:00
< p > Swiss Table 的核心是< b > 元数据与数据分开< / b > 。一组仍是 8 个槽位,但另配 8 字节的< b > 控制字< / b > :每字节对应一个槽,存哈希片段 H2( 7 位)和状态(空、满、墓碑)。控制字连续成片,键和值则是按槽交错的(每槽先 key 后 elem) , 查找时只碰控制字。< / p >
2026-10-25 17:16:48 +08:00
< p > 哈希切成两段: H1 选表和起始组, H2 在组内筛槽。8 个 H2 挤在一个 64 位字里,所以能< b > 一次比较 8 个槽< / b > :把目标 H2 摊成 8 字节常量与控制字异或,再找零字节得到位图,是 1 的位就是命中的槽——有 SIMD 编成向量指令,没有也就几条位运算。比完整键只在最后一步。< / p >
2026-10-21 14:11:30 +08:00
< div class = "tablewrap" >
< table >
< thead > < tr > < th > 维度< / th > < th > ≤ 1.23( hmap/bmap) < / th > < th > ≥ 1.24( Swiss Table) < / th > < / tr > < / thead >
< tbody >
< tr > < td > 冲突解决< / td > < td > 桶内线性 + 溢出链< / td > < td > 组内扫描 + 组间二次探测< / td > < / tr >
< tr > < td > 元数据< / td > < td > < code > tophash [8]uint8< / code > 存在桶内< / td > < td > 独立控制字,每组 8 字节< / td > < / tr >
< tr > < td > 组内筛选< / td > < td > 逐字节比较 tophash< / td > < td > 一次位运算比较 8 个 H2< / td > < / tr >
< tr > < td > 冲突链< / td > < td > 溢出桶指针,可能多次跳转< / td > < td > 探测序列,最多几次组跳转< / td > < / tr >
< tr > < td > 删除< / td > < td > 置 < code > emptyOne< / code > < / td > < td > 置墓碑,插入优先复用< / td > < / tr >
< tr > < td > 扩容< / td > < td > 全表翻倍 / 等量整理< / td > < td > 单表翻倍,或按高位 split< / td > < / tr >
< tr > < td > 遍历无序< / td > < td > 是< / td > < td > 是< / td > < / tr >
< tr > < td > 并发写< / td > < td > fatal error< / td > < td > fatal error( 语义未变) < / td > < / tr >
< / tbody >
< / table >
< / div >
2026-10-25 17:16:48 +08:00
< p > 冲突处理从挂链变成探测:当前组 8 个槽看完还没找到,就按< b > 二次探测< / b > 跳到下一组, 步长按三角数增长( 0、1、3、6、10……) , 既能覆盖所有组, 又让相邻的键散开。具体公式各版本可能微调, 别背常量。< / p >
2026-11-03 21:17:47 +08:00
< p > 扩容也变了: map 可以由多张表组成,小 map 只有一个 group、连目录都没有; 超出单表上限后不再无限翻倍, 而是按下一位哈希< b > 分成两张< / b > ,由目录按高位选表——扩容只影响一张表,「渐进」的粒度从桶变成表。墓碑也计入负载:已用加墓碑超阈值就重排,否则探测链会被墓碑拖长。< / p >
2026-10-25 17:16:48 +08:00
< figure class = "figure" >
< svg viewBox = "0 0 720 400" role = "img" aria-label = "Swiss Table 的一组: 8 字节控制字与 8 个键、8 个值各自连续存放;把目标 H2 摊成 8 字节与控制字异或得到位图,只有位为 1 的槽才去比完整键" >
< defs >
< marker id = "ar7c" viewBox = "0 0 10 10" refX = "9" refY = "5" markerWidth = "7" markerHeight = "7" orient = "auto-start-reverse" >
< path d = "M0,0 L10,5 L0,10 z" fill = "var(--muted)" / >
< / marker >
< / defs >
< text x = "360" y = "28" text-anchor = "middle" font-size = "13" fill = "var(--ink)" > 一组 = 8 个槽位:控制字先筛,键最后才比< / text >
< text x = "36" y = "72" font-size = "12" fill = "var(--muted)" > 控制字< / text >
< text x = "36" y = "128" font-size = "12" fill = "var(--muted)" > 键< / text >
< text x = "36" y = "184" font-size = "12" fill = "var(--muted)" > 值< / text >
< rect x = "104" y = "44" width = "68" height = "46" rx = "4" fill = "var(--soft)" stroke = "var(--line)" / >
< text x = "138" y = "73" text-anchor = "middle" font-size = "13" fill = "var(--ink)" > 4f< / text >
< rect x = "178" y = "44" width = "68" height = "46" rx = "4" fill = "var(--brand-soft)" stroke = "var(--brand)" / >
< text x = "212" y = "73" text-anchor = "middle" font-size = "13" fill = "var(--brand-ink)" > 8a< / text >
< rect x = "252" y = "44" width = "68" height = "46" rx = "4" fill = "var(--soft)" stroke = "var(--line)" / >
< text x = "286" y = "73" text-anchor = "middle" font-size = "13" fill = "var(--ink)" > 01< / text >
< rect x = "326" y = "44" width = "68" height = "46" rx = "4" fill = "var(--soft)" stroke = "var(--line)" / >
< text x = "360" y = "73" text-anchor = "middle" font-size = "13" fill = "var(--ink)" > c3< / text >
< rect x = "400" y = "44" width = "68" height = "46" rx = "4" fill = "var(--soft)" stroke = "var(--line)" / >
< text x = "434" y = "73" text-anchor = "middle" font-size = "13" fill = "var(--ink)" > 7e< / text >
< rect x = "474" y = "44" width = "68" height = "46" rx = "4" fill = "var(--soft)" stroke = "var(--line)" / >
< text x = "508" y = "73" text-anchor = "middle" font-size = "13" fill = "var(--ink)" > b2< / text >
< rect x = "548" y = "44" width = "68" height = "46" rx = "4" fill = "var(--soft)" stroke = "var(--line)" / >
< text x = "582" y = "73" text-anchor = "middle" font-size = "13" fill = "var(--ink)" > 5d< / text >
< rect x = "622" y = "44" width = "68" height = "46" rx = "4" fill = "var(--soft)" stroke = "var(--line)" / >
< text x = "656" y = "73" text-anchor = "middle" font-size = "13" fill = "var(--ink)" > 9a< / text >
< rect x = "104" y = "100" width = "68" height = "46" rx = "4" fill = "var(--card)" stroke = "var(--line)" / >
< text x = "138" y = "129" text-anchor = "middle" font-size = "12" fill = "var(--ink)" > k0< / text >
< rect x = "178" y = "100" width = "68" height = "46" rx = "4" fill = "var(--card)" stroke = "var(--brand)" / >
< text x = "212" y = "129" text-anchor = "middle" font-size = "12" fill = "var(--ink)" > k1< / text >
< rect x = "252" y = "100" width = "68" height = "46" rx = "4" fill = "var(--card)" stroke = "var(--line)" / >
< text x = "286" y = "129" text-anchor = "middle" font-size = "12" fill = "var(--ink)" > k2< / text >
< rect x = "326" y = "100" width = "68" height = "46" rx = "4" fill = "var(--card)" stroke = "var(--line)" / >
< text x = "360" y = "129" text-anchor = "middle" font-size = "12" fill = "var(--ink)" > k3< / text >
< rect x = "400" y = "100" width = "68" height = "46" rx = "4" fill = "var(--card)" stroke = "var(--line)" / >
< text x = "434" y = "129" text-anchor = "middle" font-size = "12" fill = "var(--ink)" > k4< / text >
< rect x = "474" y = "100" width = "68" height = "46" rx = "4" fill = "var(--card)" stroke = "var(--line)" / >
< text x = "508" y = "129" text-anchor = "middle" font-size = "12" fill = "var(--ink)" > k5< / text >
< rect x = "548" y = "100" width = "68" height = "46" rx = "4" fill = "var(--card)" stroke = "var(--line)" / >
< text x = "582" y = "129" text-anchor = "middle" font-size = "12" fill = "var(--ink)" > k6< / text >
< rect x = "622" y = "100" width = "68" height = "46" rx = "4" fill = "var(--card)" stroke = "var(--line)" / >
< text x = "656" y = "129" text-anchor = "middle" font-size = "12" fill = "var(--ink)" > k7< / text >
< rect x = "104" y = "156" width = "68" height = "46" rx = "4" fill = "var(--card)" stroke = "var(--line)" / >
< text x = "138" y = "185" text-anchor = "middle" font-size = "12" fill = "var(--ink)" > v0< / text >
< rect x = "178" y = "156" width = "68" height = "46" rx = "4" fill = "var(--card)" stroke = "var(--brand)" / >
< text x = "212" y = "185" text-anchor = "middle" font-size = "12" fill = "var(--ink)" > v1< / text >
< rect x = "252" y = "156" width = "68" height = "46" rx = "4" fill = "var(--card)" stroke = "var(--line)" / >
< text x = "286" y = "185" text-anchor = "middle" font-size = "12" fill = "var(--ink)" > v2< / text >
< rect x = "326" y = "156" width = "68" height = "46" rx = "4" fill = "var(--card)" stroke = "var(--line)" / >
< text x = "360" y = "185" text-anchor = "middle" font-size = "12" fill = "var(--ink)" > v3< / text >
< rect x = "400" y = "156" width = "68" height = "46" rx = "4" fill = "var(--card)" stroke = "var(--line)" / >
< text x = "434" y = "185" text-anchor = "middle" font-size = "12" fill = "var(--ink)" > v4< / text >
< rect x = "474" y = "156" width = "68" height = "46" rx = "4" fill = "var(--card)" stroke = "var(--line)" / >
< text x = "508" y = "185" text-anchor = "middle" font-size = "12" fill = "var(--ink)" > v5< / text >
< rect x = "548" y = "156" width = "68" height = "46" rx = "4" fill = "var(--card)" stroke = "var(--line)" / >
< text x = "582" y = "185" text-anchor = "middle" font-size = "12" fill = "var(--ink)" > v6< / text >
< rect x = "622" y = "156" width = "68" height = "46" rx = "4" fill = "var(--card)" stroke = "var(--line)" / >
< text x = "656" y = "185" text-anchor = "middle" font-size = "12" fill = "var(--ink)" > v7< / text >
< line x1 = "212" y1 = "206" x2 = "212" y2 = "230" stroke = "var(--muted)" marker-end = "url(#ar7c)" / >
< text x = "36" y = "256" font-size = "12" fill = "var(--muted)" > 位图< / text >
< rect x = "104" y = "236" width = "68" height = "40" rx = "4" fill = "var(--card)" stroke = "var(--line)" / >
< text x = "138" y = "261" text-anchor = "middle" font-size = "13" fill = "var(--muted)" > 0< / text >
< rect x = "178" y = "236" width = "68" height = "40" rx = "4" fill = "var(--brand-soft)" stroke = "var(--brand)" / >
< text x = "212" y = "261" text-anchor = "middle" font-size = "13" fill = "var(--brand-ink)" > 1< / text >
< rect x = "252" y = "236" width = "68" height = "40" rx = "4" fill = "var(--card)" stroke = "var(--line)" / >
< text x = "286" y = "261" text-anchor = "middle" font-size = "13" fill = "var(--muted)" > 0< / text >
< rect x = "326" y = "236" width = "68" height = "40" rx = "4" fill = "var(--card)" stroke = "var(--line)" / >
< text x = "360" y = "261" text-anchor = "middle" font-size = "13" fill = "var(--muted)" > 0< / text >
< rect x = "400" y = "236" width = "68" height = "40" rx = "4" fill = "var(--card)" stroke = "var(--line)" / >
< text x = "434" y = "261" text-anchor = "middle" font-size = "13" fill = "var(--muted)" > 0< / text >
< rect x = "474" y = "236" width = "68" height = "40" rx = "4" fill = "var(--card)" stroke = "var(--line)" / >
< text x = "508" y = "261" text-anchor = "middle" font-size = "13" fill = "var(--muted)" > 0< / text >
< rect x = "548" y = "236" width = "68" height = "40" rx = "4" fill = "var(--card)" stroke = "var(--line)" / >
< text x = "582" y = "261" text-anchor = "middle" font-size = "13" fill = "var(--muted)" > 0< / text >
< rect x = "622" y = "236" width = "68" height = "40" rx = "4" fill = "var(--card)" stroke = "var(--line)" / >
< text x = "656" y = "261" text-anchor = "middle" font-size = "13" fill = "var(--muted)" > 0< / text >
< text x = "360" y = "304" text-anchor = "middle" font-size = "12" fill = "var(--ink)" > 目标 H2 摊成 8 字节,与控制字异或,找出等于 0 的字节< / text >
< text x = "360" y = "328" text-anchor = "middle" font-size = "12" fill = "var(--ink)" > 位为 1 才是候选槽:只有这一列去比完整键< / text >
< text x = "360" y = "352" text-anchor = "middle" font-size = "11" fill = "var(--muted)" > 控制字每字节 = 1 位状态 + 7 位 H2, 所以 8 个槽只占 8 字节< / text >
< / svg >
2026-11-03 21:17:47 +08:00
< div class = "figcap" > < b > 图 3< / b > · 新实现:控制字连续成片,键和值按槽交错(图为示意);先拿 H2 一次比 8 个槽得到位图,只对位为 1 的槽比完整键。< / div >
2026-10-25 17:16:48 +08:00
< / figure >
< p > < span class = "tag" > 代价< / span > 代价有两层:实现复杂——探测、墓碑、分表、目录任一环出错都是数据错乱;内部布局也全变了,靠 linkname 或按偏移读 hmap 的代码在 1.24 升级时直接编译失败或行为异常。< / p >
2026-10-21 14:11:30 +08:00
< div class = "box case" >
< span class = "bt" > 升级 1.24 的真实风险:动了内部布局的代码会挂< / span >
< p > 1.24 发布后有项目升级时发现,用 < code > //go:linkname< / code > 直接调 < code > runtime.mapaccess1< / code >
或按偏移读 < code > hmap.B< / code > 的库编译失败、行为异常,因为符号和布局都变了。教训:
< strong > 内部结构是运行时实现细节,不是 API< / strong > ,需要高性能只读结构就自己写。< / p >
< / div >
2026-10-25 17:16:48 +08:00
< p class = "take" > < b > 一句话:< / b > 新实现把元数据和控制数据分开,先比 8 个哈希片段、再比键;版本上 1.24 起默认、1.26 起唯一。< / p >
2026-10-21 14:11:30 +08:00
< h3 id = "sec-7-8" > 7.8 map 并发安全吗?三种方案< / h3 >
2026-10-25 17:16:48 +08:00
< p > < span class = "tag" > 现象< / span > 写个小程序,两个 goroutine 往同一个 map 里塞键,跑起来输出 < code > fatal error: concurrent map writes< / code > ,进程直接退出:后面的 defer 一句没打,退出码是 2。< / p >
2026-11-03 21:17:47 +08:00
< p > < span class = "tag" > 机制< / span > 运行时有个「正在写」标志: 1.23 及以前是 hmap 标志位里的 < code > hashWriting< / code > , 1.24 起是 < code > maps.Map.writing< / code > 。写开始时把它异或 1( toggle, 不是单纯置位) , 写的过程中又有人来写或来读, 就报致命错误。它只是 fail-fast 探测,< b > 不是同步机制< / b > ——两个写者完全可能都在对方翻转标志前通过检查,谁都没触发,结构却已经坏了。< / p >
2026-10-21 14:11:30 +08:00
< ol class = "steps" >
< li > < b > < code > sync.RWMutex< / code > 包一层< / b > :最通用,语义最清晰,读多写少时多个读可并发。< / li >
< li > < b > < code > sync.Map< / code > < / b > : 读路径基本无锁, 适合读多写少、key 稳定的场景(见 7.9)。< / li >
< li > < b > 分片锁< / b > :拆成 N 个小 map 各配一把锁,按 key 哈希选分片,把竞争降低 N 倍。< / li >
< / ol >
< p > 第一种最常见,但别< strong > 把内部 map 的引用泄露出去< / strong > :一旦某个方法返回 < code > map[string]int< / code > ,
调用方就能绕过锁直接读写,封装的锁等于没有。< / p >
< pre data-lang = "go" data-name = "sharded_map.go: 32 分片并发 map" > const shardCount = 32
type shard struct {
mu sync.RWMutex
m map[string]int
}
type ShardedMap struct {
shards [shardCount]shard
}
func NewShardedMap() *ShardedMap {
s := & ShardedMap{}
for i := range s.shards {
s.shards[i].m = make(map[string]int)
}
return s
}
// FNV-1a, 手写避免每次调用都分配一个 hasher
func hashKey(key string) uint32 {
var h uint32 = 2166136261
for i := 0; i < len(key); i++ {
h ^= uint32(key[i])
h *= 16777619
}
return h
}
func (s *ShardedMap) Get(key string) (int, bool) {
sh := & s.shards[hashKey(key)& (shardCount-1)]
sh.mu.RLock()
defer sh.mu.RUnlock()
v, ok := sh.m[key]
return v, ok
}
func (s *ShardedMap) Set(key string, v int) {
sh := & s.shards[hashKey(key)& (shardCount-1)]
sh.mu.Lock()
defer sh.mu.Unlock()
sh.m[key] = v
}< / pre >
< p > 分片数不是越多越好:分片多了每个 map 更小、扩容更频繁,总内存也上升(每个 map 都有自己的
2026-11-03 21:17:47 +08:00
运行时结构和最小桶/组数组:≤ 1.23 是 < code > hmap< / code > , 1.24 起是 table + group( 小 map 连 table 都没有,只有一个 group) , 经验值是 16~ 256。另外分片锁< strong > 不提供跨分片的原子操作< / strong > :
2026-10-21 14:11:30 +08:00
统计总数或遍历全部,得把所有分片的锁都拿一遍,并且约定加锁顺序,否则会死锁。< / p >
2026-10-25 17:16:48 +08:00
< p > < span class = "tag" > 代价< / span > 三种方案的账单不一样: 读写锁每次读都要动一次原子量; sync.Map 用更高内存和丢失类型安全,换读路径无锁;分片锁把内存和扩容次数乘上分片数。选型看读写比例和 key 集合稳不稳,不是看哪个更快。< / p >
2026-10-21 14:11:30 +08:00
< div class = "box ok" >
< span class = "bt" > 用 < code > -race< / code > 验证,别靠「跑起来没崩」< / span >
< p > 竞争检测器记录每次内存访问并做 happens-before 分析,发现两个 goroutine 无同步访问同一地址就报警。
命令是 < code > go test -race ./...< / code > 或 < code > go run -race main.go< / code > ,代价是慢 5~ 20 倍、
内存涨几倍,所以只在测试和预发开。它能抓到「没崩但已经脏了」的并发,
2026-10-21 15:21:43 +08:00
这正是写标志(≤ 1.23 的 < code > hashWriting< / code > 、1.24 起的 < code > writing< / code > )检测不到的部分。< / p >
2026-10-21 14:11:30 +08:00
< / div >
2026-10-25 17:16:48 +08:00
< div class = "box warn" >
< span class = "bt" > 易错点 · 它是致命错误,不是 panic< / span >
< p > 走的是 < code > throw< / code > 而不是 < code > panic< / code > :不展开 defer、< code > recover< / code > 接不住,进程直接退出。因为并发写会把控制字、计数、桶指针改坏,继续跑可能是死循环或野指针,崩溃反而最安全。所以「用 recover 兜住 map 并发」从一开始就不成立,验证只能靠 < code > go test -race< / code > 。< / p >
< / div >
2026-10-21 14:11:30 +08:00
< pre data-lang = "text" data-name = "go test -race 的典型输出" > $ go test -race ./...
==================
WARNING: DATA RACE
Write at 0x00c0000b4180 by goroutine 8:
runtime.mapassign_faststr()
/usr/local/go/src/runtime/map_faststr.go:203 +0x0f4
main.TestConcurrentWrite.func1()
/app/safe_map_test.go:14 +0x64
Previous write at 0x00c0000b4180 by goroutine 7:
runtime.mapassign_faststr()
/usr/local/go/src/runtime/map_faststr.go:203 +0x0f4
==================
--- FAIL: TestConcurrentWrite (0.00s)< / pre >
2026-10-25 17:16:48 +08:00
< p class = "take" > < b > 一句话:< / b > 原生 map 并发写是致命错误, 只能靠锁、sync.Map 或分片;验证靠 race 检测器,不靠运气。< / p >
2026-10-21 14:11:30 +08:00
< h3 id = "sec-7-9" > 7.9 sync.Map 与 map 的区别< / h3 >
2026-10-25 17:16:48 +08:00
< p > < span class = "tag" > 现象< / span > 给「命中已有键」写个基准测试,< code > -benchmem< / code > 会显示 sync.Map 比拿读锁的原生 map 略快;把负载换成写多读少,数字立刻反过来。另外它没有 < code > Len()< / code > ,想要个数只能 Range 一遍。< / p >
< p > < span class = "tag" > 机制< / span > 因为它的设计目标只有一个:< b > 让读路径不加锁< / b > 。1.23 及以前内部是三层——< code > read< / code > (原子指针包着的只读 map) 、< code > dirty< / code > (普通 map, 读写都要互斥锁) 、< code > misses< / code > (读未命中、转去查 dirty 的次数)。< / p >
2026-10-21 15:54:40 +08:00
< div class = "box note" >
< span class = "bt" > 版本提示:默认实现换过一次< / span >
< p > 下面描述的 < code > read< / code > /< code > dirty< / code > /< code > misses< / code > /< code > entry.p< / code > 是
< strong > Go 1.23 及以前< / strong > 的实现。Go 1.24 引入新的并发 map
< code > internal/sync.HashTrieMap< / code > ,以 < code > GOEXPERIMENT=synchashtriemap< / code > 形式可选;
< strong > Go 1.25 起它成为 < code > sync.Map< / code > 的默认实现< / strong > ——
< code > type Map struct { _ noCopy; m isync.HashTrieMap[any, any] }< / code > ,
那四个字段在 1.25 里已经不存在; Go 1.26 删掉了旧实现。本站以 1.25 为基线,
读源码时直接看 < code > internal/sync/hashtriemap.go< / code > 。< / p >
< / div >
2026-10-25 17:16:48 +08:00
< p > 读先查 < code > read< / code > ,命中即返回,一次原子读;没命中且 < code > amended< / code > 为真,就加锁查 < code > dirty< / code > ,顺便把 < code > misses< / code > 加一。攒到 < code > dirty< / code > 的长度时,把 < code > dirty< / code > 整体提升成新的 < code > read< / code > ——一次 O(n) 指针拷贝。这就是「读多写少才快」的根源。< / p >
< p > 写分两种:改已在 < code > read< / code > 里的键,直接 CAS, < b > 不加锁< / b > ;写新键必须加锁写 < code > dirty< / code > ,并把 < code > read< / code > 标记成已修订。值还有三态(正常指针、已删但仍留在 dirty、彻底删除) , 为的是让「删了又被读」不必升级成加锁。< / p >
2026-10-21 14:11:30 +08:00
< pre data-lang = "go" data-name = "sync_map.go: LoadOrStore 的语义" > var m sync.Map
m.Store("a", 1)
m.Store("a", 2) // 覆盖,最终是 2
v, ok := m.Load("a") // 2, true
v, ok = m.Load("nope") // nil, false
// LoadOrStore: 存在则返回旧值 + true; 不存在则存入并返回新值 + false
// 整个"查 + 存"是原子的,两个 goroutine 同时调,只有一个拿到 loaded=false
actual, loaded := m.LoadOrStore("a", 100) // actual=2, loaded=true
actual, loaded = m.LoadOrStore("b", 100) // actual=100, loaded=false
m.Range(func(k, v any) bool {
// 注意: Range 不保证一致性快照,遍历期间别的 goroutine 可能正在改
return true // 返回 false 提前结束
})< / pre >
< div class = "tablewrap" >
< table >
< thead > < tr > < th > 对比项< / th > < th > < code > map< / code > + < code > RWMutex< / code > < / th > < th > < code > sync.Map< / code > < / th > < / tr > < / thead >
< tbody >
< tr > < td > 类型安全< / td > < td > 强类型 < code > map[K]V< / code > < / td > < td > < code > any< / code > ,取值要断言 + 装箱< / td > < / tr >
2026-10-21 15:54:40 +08:00
< tr > < td > 读性能< / td > < td > 要拿读锁,有竞争< / td > < td > 命中只读结构时无锁( 1.23 及以前是 < code > read< / code > , 1.25 起是 HashTrieMap 的只读桶)< / td > < / tr >
2026-11-03 21:17:47 +08:00
< tr > < td > 写性能< / td > < td > 一把锁,简单直接< / td > < td > 1.23 及以前:新 key 加锁、可能 O(n) 提升; 1.25 起 HashTrieMap 按节点加锁(不是分片),没有全量提升< / td > < / tr >
2026-10-21 14:11:30 +08:00
< tr > < td > < code > len< / code > < / td > < td > O(1)< / td > < td > 没有 < code > len< / code > ,只能 < code > Range< / code > 数, O(n)< / td > < / tr >
< tr > < td > 遍历< / td > < td > 持锁遍历,快照一致< / td > < td > < code > Range< / code > 不保证一致< / td > < / tr >
< tr > < td > 适用< / td > < td > 通用,写多也能用< / td > < td > 读远多于写、key 稳定< / td > < / tr >
< / tbody >
< / table >
< / div >
2026-10-25 17:16:48 +08:00
< p > 官方推荐两类场景:键只写一次、之后反复读(配置缓存),以及多个 goroutine 各读写互不相交的键。写多、键频繁增删、需要 < code > len< / code > 、需要一致遍历、需要强类型——都退回原生 map 加读写锁。< / p >
< p > < span class = "tag" > 代价< / span > 键值都是 < code > any< / code > ,每次存取要装箱、取值要断言;内部含锁,< b > 不能拷贝< / b > ,传值会触发 copylocks 警告甚至死锁;< code > Range< / code > 不保证一致快照, 遍历时看到的是新旧混合。1.23 及以前值存指针,还多一层间接寻址。< / p >
< p class = "take" > < b > 一句话:< / b > sync.Map 用两次内存和类型安全,换一条无锁读路径;键稳定、读远多于写才划算。< / p >
2026-10-21 14:11:30 +08:00
< h3 id = "sec-7-10" > 7.10 哈希攻击与随机种子< / h3 >
2026-10-25 17:16:48 +08:00
< p > < span class = "tag" > 现象< / span > 给字符串键的 map 写个基准,加 < code > GODEBUG=cpu.aes=off< / code > 再跑一遍:哈希从 < code > aeshash< / code > 退到 < code > memhash< / code > , ns/op 变了。同一个程序、同一批键,只是哈希函数换了——哈希和种子都是可替换的实现细节,不是语言语义。< / p >
< p > < span class = "tag" > 机制< / span > 哈希表平均常数时间,最坏是 O(n): 所有键落到一个桶, 查找要沿链走到底。若键由外部控制( 表单字段名、HTTP 头名),攻击者就能故意造这种输入,这就是< b > 哈希洪水攻击< / b > , 2011 年前后 PHP、Java、Ruby 都栽过。< / p >
2026-10-21 15:21:43 +08:00
< p > Go 的防御是< strong > 哈希种子随机化< / strong > :每个 map 创建时随机生成种子——≤ 1.23 是 < code > makemap< / code > 里的
< code > hash0< / code > ,之后每次算哈希都传进去(< code > alg.hash(key, uintptr(h.hash0))< / code > ) ; 1.24 起换成
< code > maps.Map.seed< / code > ( < code > m.seed = uintptr(rand())< / code > ,算哈希时 < code > typ.Hasher(key, m.seed)< / code > )。
同一个 key 在两个进程里哈希完全不同,攻击者即便清楚算法也< strong > 无法离线构造碰撞< / strong > ——他不知道种子。
2026-10-21 14:11:30 +08:00
种子只生成一次,每次哈希计算量不变,防御几乎免费。< / p >
2026-10-25 17:16:48 +08:00
< p > 第二层在哈希函数本身: amd64、arm64 有 AES 指令时,字符串和字节切片走 < code > aeshash< / code > ——键分块与种子一起过几轮 < code > AESENC< / code > ,一条指令吃 16 字节,而且改一个 bit 输出全变;没有硬件 AES 的平台退化成 < code > memhash< / code > (乘法加移位),安全性仍靠种子。< / p >
< p > 第三层是结构兜底:旧实现每桶 8 槽、超了挂溢出桶,溢出桶一多就触发等量扩容收紧链,装载因子超过 6.5 就翻倍;新实现 8 槽一组、三角探测,墓碑计入负载,超阈值就重排或分表。就算真能造出冲突,扩容也会持续把元素打散。< / p >
< p > < span class = "tag" > 代价< / span > 「提高攻击成本」不等于「消灭最坏情况」:种子只有 4 到 8 字节,能反复探测响应时间的攻击者理论上仍可暴力搜索;种子也不改变单桶的长度上限。所以键由外部控制、又对延迟敏感的服务,仍要限制键的数量和长度。< / p >
< p class = "take" > < b > 一句话:< / b > 种子让碰撞无法离线构造, AES 哈希让它更贵,结构兜底让它有上限——但最坏情况依然存在。< / p >
2026-10-21 14:11:30 +08:00
< div class = "box tip" >
< span class = "bt" > 面试怎么答「Go 怎么防哈希攻击 / 为什么不需要红黑树」< / span >
< p > 先纠正前提: 「Go 的内置 map 不用红黑树,那是 Java 的方案——Java 8 在链长 > 8 且容量 ≥ 64 时树化,
把最坏 O(n) 兜到 O(log n); Go 不在结构上兜底,而是< strong > 降低最坏情况被触发的概率< / strong > :每桶 8 槽 +
溢出链 + 每个 map 随机 < code > hash0< / code > + 字符串哈希用 AES 指令,让攻击者无法离线构造碰撞。
1.24 换成 Swiss Table 后思路没变。」追问「随机化影响性能吗」,答「种子只在建 map 时生成一次,
每次哈希的计算量不变」。< / p >
< / div >
< div class = "box note" >
< span class = "bt" > 版本差异速记< / span >
< ul >
< li > < b > ≤ 1.23< / b > : < code > hmap< / code > + < code > bmap< / code > + 溢出桶;装载因子 6.5 触发翻倍扩容,溢出桶过多触发等量扩容。< / li >
2026-10-21 15:21:43 +08:00
< li > < b > 1.24 起< / b > : Swiss Table( < code > internal/runtime/maps< / code > )默认启用,控制字 + group + 二次探测 + table 级 split,
扩容判定改成看单表的已用槽位与墓碑;此时 < code > GOEXPERIMENT=noswissmap< / code > 仍可退回旧实现。< / li >
< li > < b > 1.25< / b > : map 实现与 1.24 相同,本章以它为基准;< code > noswissmap< / code > 也仍然保留。< / li >
< li > < b > 1.26 起< / b > :删除 < code > noswissmap< / code > 与 < code > runtime/map_noswiss.go< / code > ,旧 < code > hmap< / code > /< code > bmap< / code > 彻底消失。< / li >
2026-10-21 14:11:30 +08:00
< li > < b > 没变的< / b > :遍历仍无序,并发写仍 fatal error, < code > len< / code > 仍 O(1), < code > delete< / code > 语义不变。< / li >
< / ul >
< / div >
2026-10-25 17:16:48 +08:00
< h2 id = "ch7-sum" > 全章回顾:从症状倒推实现< / h2 >
< div class = "tablewrap" >
< table >
< thead > < tr > < th > 症状< / th > < th > 先查什么< / th > < th > 回哪节< / th > < / tr > < / thead >
< tbody >
< tr > < td > 每次遍历顺序都不同< / td > < td > 是不是依赖了 range 顺序;要稳定就自己收集键排序< / td > < td > 7.6< / td > < / tr >
< tr > < td > < code > m[k].X = 1< / code > 编译不过< / td > < td > 元素不可寻址,整体写回或改存指针< / td > < td > 7.4< / td > < / tr >
< tr > < td > 进程突然退出,报 concurrent map writes< / td > < td > 有没有裸 map 跨 goroutine 读写,加锁或分片< / td > < td > 7.8< / td > < / tr >
< tr > < td > 怀疑扩容期间读到了旧值< / td > < td > 普通读不会读到旧值,查是不是读了副本或没同步的变量< / td > < td > 7.5< / td > < / tr >
< tr > < td > 觉得 < code > len< / code > 慢< / td > < td > 不慢,读的是计数;慢在别处< / td > < td > 7.2< / td > < / tr >
< tr > < td > 删了很多键,内存不降< / td > < td > 桶数组不缩容,等量扩容只整理;考虑重建 map< / td > < td > 7.5< / td > < / tr >
< tr > < td > 读多写少却还拿读写锁< / td > < td > 键集合稳定才换 sync.Map, 否则更慢< / td > < td > 7.9< / td > < / tr >
< tr > < td > 单键查询 P99 抖动< / td > < td > 键是不是外部可控、是不是哈希集中< / td > < td > 7.10< / td > < / tr >
< / tbody >
< / table >
< / div >
< p > 相邻的对照:切片扩容与 map 扩容的相似和不同可以对着 < a href = "06-slice.html#sec-6-4" > 6.4< / a > 看;锁与 sync.Map 的取舍和 < a href = "10-sync.html#sec-10-10" > 10.10< / a > 是同一套判断;想先补齐 goroutine 的退出模型,回看 < a href = "01-goroutine.html#sec-1-8" > 1.8< / a > 。< / p >
< div class = "box tip" >
< span class = "bt" > 面试怎么收尾< / span >
2026-11-03 21:17:47 +08:00
< p > 三句话收口:先说结构(桶加 tophash, 或控制字加组) , 再说成本( 装载因子旧实现 6.5、新实现每组 7/8; 渐进扩容; 长度 O(1)) , 最后说边界( 遍历无序、并发写致命、元素不可寻址) 。被追问版本就报三代: 1.23 及以前 hmap, 1.24 和 1.25 默认 Swiss, 1.26 只剩 Swiss。< / p >
2026-10-25 17:16:48 +08:00
< / div >
2026-10-21 14:11:30 +08:00
< / article >
< nav class = "pager" >
< a class = "prev" href = "06-slice.html" > < span class = "k" > ← 上一章< / span > < span class = "v" > 第 6 章 · slice: 视图、扩容与共享底层数组< / span > < / a >
< a class = "next" href = "08-channel.html" > < span class = "k" > 下一章 →< / span > < span class = "v" > 第 8 章 · channel: CSP 的载体与并发编排< / span > < / a >
< / nav >
< p class = "foot" >
Go 八股 · 第 7 章 map: 从 hmap/bmap 到 1.24 Swiss Table< br >
< a href = "index.html" > 总目录< / a > · < a href = "../../SRE工程师/sre-learning-path/index.html" > SRE 学习路径< / a >
< / p >
< / main >
< / div >
< button id = "toTop" title = "回到顶部" > ↑< / button >
< script src = "assets/doc.js" > < / script >
< script src = "../../assets/back.js" data-portal-back = "knowledge/go" data-portal-label = "知识库 › Go 八股知识库" > < / script >
< / body >
< / html >