Hash Tables:open addressing、tombstone 与 interning
Crafting Interpreters:Hash Tables
本章实现 clox 的 hash table:用 open addressing 管理 key/value entries,并为字符串 interning 提供高效查找。
TL;DR
- hash table 把 key 映射为 bucket index,平均 O(1) 查找依赖良好的 hash 与受控 load factor。
- collision 无法避免;clox 使用 open addressing 和线性探测,把 entry 放在同一数组中。
- 删除 entry 不能简单清空 bucket,否则会截断后续 probe sequence;tombstone 用来保留查找路径。
- table 扩容时重新计算所有 entry 的位置,空 tombstone 不会被复制。
- string interning 让相同内容的字符串共享对象,从而加速 equality、减少内存并复用 hash。
目录
| 章节 | 内容 |
|---|---|
| An array of buckets | bucket 与 load factor |
| Collision resolution | chaining 与 open addressing |
| Hash functions | 字符串哈希 |
| Building a hash table | 插入、查找、删除与扩容 |
| String interning | canonical string |
| Challenges | 扩展练习 |
An array of buckets
hash table 由 bucket array 构成。hash function 把 key 转成整数,再用 table capacity 计算初始 index:

两个 key 可能得到同一个 bucket:

Load factor and wrapped keys
当 table 过满,collision chain 变长,查找成本上升。clox 设定最大 load factor,达到阈值就扩容。index 到数组末尾后需要 wrap 到开头:

Collision resolution
Separate chaining
separate chaining 让每个 bucket 保存链表头;冲突 key 追加到链表:

它删除简单,却需要 node allocation 和 pointer chasing。
Open addressing
open addressing 把所有 entry 放在同一个 array。发生 collision 时按 probe sequence 寻找下一个空 bucket。clox 使用线性探测:index、index+1、……,越过末尾就 wrap。
插入过程会逐步填充相邻 bucket:







Hash functions
字符串 hash 应满足:相同字符串得到相同 hash;不同字符串尽量分散;计算速度足够快。clox 使用一类常见的逐字节 hash,将字符累积到固定宽度整数中。
hash 只决定 probe 的起点,不保证 key 相等。查找时仍需比较 hash、长度和字符内容。
Building a hash table
table entry 保存 key 与 value。空 bucket 的 key 为 NULL;tombstone 的 key 非 NULL 而 value 为特殊 nil,或使用明确的 tombstone 状态。
插入时记录第一个 tombstone,但继续 probe,直到确认 table 中不存在同 key;若找到同 key,则更新 value。这样能复用最早的删除槽位,同时避免重复 key。
扩容通常把 capacity 翻倍,分配新 bucket array,再把旧 entries 重新插入。不能直接 memcpy,因为新的 capacity 改变了 hash 到 index 的映射。
查找时遇到 NULL 表示 key 不存在;遇到 tombstone 必须继续 probe;遇到相同 key 才返回 value。删除时写入 tombstone,而不是 NULL:

直接清空会破坏 probe chain:

使用 tombstone 后,后续 key 仍能沿原路径找到:


tombstone 数量也计入 load factor;否则 table 可能看似未满,却因为大量 tombstone 导致查找缓慢。扩容或重建 table 可以清除它们。
String interning
interning table 保存所有已分配的 canonical strings。创建新 string 前,先按 hash、长度和字符内容查找已有对象;找到就释放新 buffer 并返回旧对象,否则把新对象加入 intern table。
这使字符串 equality 可以先比较 pointer:只有相同内容才会共享 canonical object。intern table 的引用处理必须与 GC 协作,避免 table 本身让所有字符串永久存活。
Challenges
1. Robin Hood hashing
实现 Robin Hood hashing,比较 probe length、最坏查找和删除策略。
2. Incremental resizing
把扩容工作分散到多次操作中,避免一次 insert 触发很长的 pause。
3. Weak interning table
实现不会阻止未使用 string 被 GC 回收的 weak table。
原文代码片段
本节按官方页面顺序保留本章所有 grammar、C 和测试代码片段,便于与上文译文逐段对照。
参考资料
Code block 1
#ifndef clox_table_h
#define clox_table_h
#include "common.h"
#include "value.h"
typedef struct {
int count;
int capacity;
Entry* entries;
} Table;
#endif
Code block 2
#include "value.h"
Code block 3
typedef struct {
ObjString* key;
Value value;
} Entry;
Code block 4
typedef struct {
Code block 5
} Table;
Code block 6
void initTable(Table* table);
Code block 7
#endif
Code block 8
#include <stdlib.h>
#include <string.h>
#include "memory.h"
#include "object.h"
#include "table.h"
#include "value.h"
void initTable(Table* table) {
table->count = 0;
table->capacity = 0;
table->entries = NULL;
}
Code block 9
void initTable(Table* table);
Code block 10
void freeTable(Table* table);
Code block 11
#endif
Code block 12
void freeTable(Table* table) {
FREE_ARRAY(Entry, table->entries, table->capacity);
initTable(table);
}
Code block 13
char* chars;
Code block 14
uint32_t hash;
Code block 15
};
Code block 16
static ObjString* allocateString(char* chars, int length,
uint32_t hash) {
Code block 17
ObjString* string = ALLOCATE_OBJ(ObjString, OBJ_STRING);
Code block 18
string->chars = chars;
Code block 19
string->hash = hash;
Code block 20
return string;
}
Code block 21
ObjString* copyString(const char* chars, int length) {
Code block 22
uint32_t hash = hashString(chars, length);
Code block 23
char* heapChars = ALLOCATE(char, length + 1);
Code block 24
memcpy(heapChars, chars, length);
heapChars[length] = '\0';
Code block 25
return allocateString(heapChars, length, hash);
Code block 26
}
Code block 27
ObjString* takeString(char* chars, int length) {
Code block 28
uint32_t hash = hashString(chars, length);
return allocateString(chars, length, hash);
Code block 29
}
Code block 30
static uint32_t hashString(const char* key, int length) {
uint32_t hash = 2166136261u;
for (int i = 0; i < length; i++) {
hash ^= (uint8_t)key[i];
hash *= 16777619;
}
return hash;
}
Code block 31
void freeTable(Table* table);
Code block 32
bool tableSet(Table* table, ObjString* key, Value value);
Code block 33
#endif
Code block 34
bool tableSet(Table* table, ObjString* key, Value value) {
Entry* entry = findEntry(table->entries, table->capacity, key);
bool isNewKey = entry->key == NULL;
if (isNewKey) table->count++;
entry->key = key;
entry->value = value;
return isNewKey;
}
Code block 35
bool tableSet(Table* table, ObjString* key, Value value) {
Code block 36
if (table->count + 1 > table->capacity * TABLE_MAX_LOAD) {
int capacity = GROW_CAPACITY(table->capacity);
adjustCapacity(table, capacity);
}
Code block 37
Entry* entry = findEntry(table->entries, table->capacity, key);
Code block 38
#include "value.h"
Code block 39
#define TABLE_MAX_LOAD 0.75
Code block 40
void initTable(Table* table) {
Code block 41
static Entry* findEntry(Entry* entries, int capacity,
ObjString* key) {
uint32_t index = key->hash % capacity;
for (;;) {
Entry* entry = &entries[index];
if (entry->key == key || entry->key == NULL) {
return entry;
}
index = (index + 1) % capacity;
}
}
Code block 42
static void adjustCapacity(Table* table, int capacity) {
Entry* entries = ALLOCATE(Entry, capacity);
for (int i = 0; i < capacity; i++) {
entries[i].key = NULL;
entries[i].value = NIL_VAL;
}
table->entries = entries;
table->capacity = capacity;
}
Code block 43
entries[i].value = NIL_VAL;
}
Code block 44
for (int i = 0; i < table->capacity; i++) {
Entry* entry = &table->entries[i];
if (entry->key == NULL) continue;
Entry* dest = findEntry(entries, capacity, entry->key);
dest->key = entry->key;
dest->value = entry->value;
}
Code block 45
table->entries = entries;
Code block 46
dest->value = entry->value;
}
Code block 47
FREE_ARRAY(Entry, table->entries, table->capacity);
Code block 48
table->entries = entries;
Code block 49
bool tableSet(Table* table, ObjString* key, Value value);
Code block 50
void tableAddAll(Table* from, Table* to);
Code block 51
#endif
Code block 52
void tableAddAll(Table* from, Table* to) {
for (int i = 0; i < from->capacity; i++) {
Entry* entry = &from->entries[i];
if (entry->key != NULL) {
tableSet(to, entry->key, entry->value);
}
}
}
Code block 53
void freeTable(Table* table);
Code block 54
bool tableGet(Table* table, ObjString* key, Value* value);
Code block 55
bool tableSet(Table* table, ObjString* key, Value value);
Code block 56
bool tableGet(Table* table, ObjString* key, Value* value) {
if (table->count == 0) return false;
Entry* entry = findEntry(table->entries, table->capacity, key);
if (entry->key == NULL) return false;
*value = entry->value;
return true;
}
Code block 57
bool tableSet(Table* table, ObjString* key, Value value);
Code block 58
bool tableDelete(Table* table, ObjString* key);
Code block 59
void tableAddAll(Table* from, Table* to);
Code block 60
bool tableDelete(Table* table, ObjString* key) {
if (table->count == 0) return false;
// Find the entry.
Entry* entry = findEntry(table->entries, table->capacity, key);
if (entry->key == NULL) return false;
// Place a tombstone in the entry.
entry->key = NULL;
entry->value = BOOL_VAL(true);
return true;
}
Code block 61
for (;;) {
Entry* entry = &entries[index];
Code block 62
if (entry->key == NULL) {
if (IS_NIL(entry->value)) {
// Empty entry.
return tombstone != NULL ? tombstone : entry;
} else {
// We found a tombstone.
if (tombstone == NULL) tombstone = entry;
}
} else if (entry->key == key) {
// We found the key.
return entry;
}
Code block 63
index = (index + 1) % capacity;
Code block 64
uint32_t index = key->hash % capacity;
Code block 65
Entry* tombstone = NULL;
Code block 66
for (;;) {
Code block 67
bool isNewKey = entry->key == NULL;
Code block 68
if (isNewKey && IS_NIL(entry->value)) table->count++;
Code block 69
entry->key = key;
Code block 70
}
Code block 71
table->count = 0;
Code block 72
for (int i = 0; i < table->capacity; i++) {
Code block 73
dest->value = entry->value;
Code block 74
table->count++;
Code block 75
}
Code block 76
Value* stackTop;
Code block 77
Table strings;
Code block 78
Obj* objects;
Code block 79
#include "chunk.h"
Code block 80
#include "table.h"
Code block 81
#include "value.h"
Code block 82
vm.objects = NULL;
Code block 83
initTable(&vm.strings);
Code block 84
}
Code block 85
void freeVM() {
Code block 86
freeTable(&vm.strings);
Code block 87
freeObjects();
Code block 88
string->hash = hash;
Code block 89
tableSet(&vm.strings, string, NIL_VAL);
Code block 90
return string;
Code block 91
uint32_t hash = hashString(chars, length);
Code block 92
ObjString* interned = tableFindString(&vm.strings, chars, length,
hash);
if (interned != NULL) return interned;
Code block 93
char* heapChars = ALLOCATE(char, length + 1);
Code block 94
uint32_t hash = hashString(chars, length);
Code block 95
ObjString* interned = tableFindString(&vm.strings, chars, length,
hash);
if (interned != NULL) {
FREE_ARRAY(char, chars, length + 1);
return interned;
}
Code block 96
return allocateString(chars, length, hash);
Code block 97
#include "object.h"
Code block 98
#include "table.h"
Code block 99
#include "value.h"
Code block 100
void tableAddAll(Table* from, Table* to);
Code block 101
ObjString* tableFindString(Table* table, const char* chars,
int length, uint32_t hash);
Code block 102
#endif
Code block 103
ObjString* tableFindString(Table* table, const char* chars,
int length, uint32_t hash) {
if (table->count == 0) return NULL;
uint32_t index = hash % table->capacity;
for (;;) {
Entry* entry = &table->entries[index];
if (entry->key == NULL) {
// Stop if we find an empty non-tombstone entry.
if (IS_NIL(entry->value)) return NULL;
} else if (entry->key->length == length &&
entry->key->hash == hash &&
memcmp(entry->key->chars, chars, length) == 0) {
// We found it.
return entry->key;
}
index = (index + 1) % table->capacity;
}
}
Code block 104
case VAL_NUMBER: return AS_NUMBER(a) == AS_NUMBER(b);
Code block 105
case VAL_OBJ: return AS_OBJ(a) == AS_OBJ(b);
Code block 106
default: return false; // Unreachable.
参考资料
- 原文:Hash Tables
- 系列索引
- Robert Nystrom, Crafting Interpreters,© 2015–2021
评论 (0)