目录
正在加载目录…
正在阅读专栏 Crafting Interpreters:手写解释器 第 23 篇 · 共 35 篇 · 66%

Hash Tables:open addressing、tombstone 与 interning

发布于 2026-09-16 19:18 · 最后编辑于 2026-09-17 22:07 · 版本 v2 · 字数 3,423 · 预计阅读 7 分钟 👁 12 次阅读

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 bucketsbucket 与 load factor
Collision resolutionchaining 与 open addressing
Hash functions字符串哈希
Building a hash table插入、查找、删除与扩容
String interningcanonical string
Challenges扩展练习

An array of buckets

hash table 由 bucket array 构成。hash function 把 key 转成整数,再用 table capacity 计算初始 index:

bucket array

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

collision

Load factor and wrapped keys

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

pigeons

Collision resolution

Separate chaining

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

chaining

它删除简单,却需要 node allocation 和 pointer chasing。

Open addressing

open addressing 把所有 entry 放在同一个 array。发生 collision 时按 probe sequence 寻找下一个空 bucket。clox 使用线性探测:index、index+1、……,越过末尾就 wrap。

插入过程会逐步填充相邻 bucket:

insert 1

insert 2

insert 3

insert 4

insert 5

insert 6

insert 7

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:

delete 1

直接清空会破坏 probe chain:

delete 2

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

delete 3

tombstone

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

c
#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

c
#include "value.h"

Code block 3

c
typedef struct {
  ObjString* key;
  Value value;
} Entry;

Code block 4

c
typedef struct {

Code block 5

c
} Table;

Code block 6

c
void initTable(Table* table);

Code block 7

text
#endif

Code block 8

c
#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

c
void initTable(Table* table);

Code block 10

c
void freeTable(Table* table);

Code block 11

text
#endif

Code block 12

c
void freeTable(Table* table) {
  FREE_ARRAY(Entry, table->entries, table->capacity);
  initTable(table);
}

Code block 13

text
  char* chars;

Code block 14

c
  uint32_t hash;

Code block 15

text
};

Code block 16

c
static ObjString* allocateString(char* chars, int length,
                                 uint32_t hash) {

Code block 17

c
  ObjString* string = ALLOCATE_OBJ(ObjString, OBJ_STRING);

Code block 18

text
  string->chars = chars;

Code block 19

text
  string->hash = hash;

Code block 20

c
  return string;
}

Code block 21

c
ObjString* copyString(const char* chars, int length) {

Code block 22

c
  uint32_t hash = hashString(chars, length);

Code block 23

text
  char* heapChars = ALLOCATE(char, length + 1);

Code block 24

text
  memcpy(heapChars, chars, length);
  heapChars[length] = '\0';

Code block 25

c
  return allocateString(heapChars, length, hash);

Code block 26

text
}

Code block 27

c
ObjString* takeString(char* chars, int length) {

Code block 28

c
  uint32_t hash = hashString(chars, length);
  return allocateString(chars, length, hash);

Code block 29

text
}

Code block 30

c
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

c
void freeTable(Table* table);

Code block 32

c
bool tableSet(Table* table, ObjString* key, Value value);

Code block 33

text
#endif

Code block 34

c
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

c
bool tableSet(Table* table, ObjString* key, Value value) {

Code block 36

c
  if (table->count + 1 > table->capacity * TABLE_MAX_LOAD) {
    int capacity = GROW_CAPACITY(table->capacity);
    adjustCapacity(table, capacity);
  }

Code block 37

c
  Entry* entry = findEntry(table->entries, table->capacity, key);

Code block 38

c
#include "value.h"

Code block 39

c
#define TABLE_MAX_LOAD 0.75

Code block 40

c
void initTable(Table* table) {

Code block 41

c
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

c
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

text
    entries[i].value = NIL_VAL;
  }

Code block 44

c
  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

text
  table->entries = entries;

Code block 46

text
    dest->value = entry->value;
  }

Code block 47

c
  FREE_ARRAY(Entry, table->entries, table->capacity);

Code block 48

text
  table->entries = entries;

Code block 49

c
bool tableSet(Table* table, ObjString* key, Value value);

Code block 50

c
void tableAddAll(Table* from, Table* to);

Code block 51

text
#endif

Code block 52

c
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

c
void freeTable(Table* table);

Code block 54

c
bool tableGet(Table* table, ObjString* key, Value* value);

Code block 55

c
bool tableSet(Table* table, ObjString* key, Value value);

Code block 56

c
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

c
bool tableSet(Table* table, ObjString* key, Value value);

Code block 58

c
bool tableDelete(Table* table, ObjString* key);

Code block 59

c
void tableAddAll(Table* from, Table* to);

Code block 60

c
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

c
  for (;;) {
    Entry* entry = &entries[index];

Code block 62

c
    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

text
    index = (index + 1) % capacity;

Code block 64

c
  uint32_t index = key->hash % capacity;

Code block 65

c
  Entry* tombstone = NULL;

Code block 66

text
  for (;;) {

Code block 67

text
  bool isNewKey = entry->key == NULL;

Code block 68

c
  if (isNewKey && IS_NIL(entry->value)) table->count++;

Code block 69

text
  entry->key = key;

Code block 70

text
  }

Code block 71

text
  table->count = 0;

Code block 72

c
  for (int i = 0; i < table->capacity; i++) {

Code block 73

text
    dest->value = entry->value;

Code block 74

text
    table->count++;

Code block 75

text
  }

Code block 76

c
  Value* stackTop;

Code block 77

c
  Table strings;

Code block 78

text
  Obj* objects;

Code block 79

c
#include "chunk.h"

Code block 80

c
#include "table.h"

Code block 81

c
#include "value.h"

Code block 82

text
  vm.objects = NULL;

Code block 83

c
  initTable(&vm.strings);

Code block 84

text
}

Code block 85

c
void freeVM() {

Code block 86

c
  freeTable(&vm.strings);

Code block 87

text
  freeObjects();

Code block 88

text
  string->hash = hash;

Code block 89

text
  tableSet(&vm.strings, string, NIL_VAL);

Code block 90

c
  return string;

Code block 91

c
  uint32_t hash = hashString(chars, length);

Code block 92

c
  ObjString* interned = tableFindString(&vm.strings, chars, length,
                                        hash);
  if (interned != NULL) return interned;

Code block 93

text
  char* heapChars = ALLOCATE(char, length + 1);

Code block 94

c
  uint32_t hash = hashString(chars, length);

Code block 95

c
  ObjString* interned = tableFindString(&vm.strings, chars, length,
                                        hash);
  if (interned != NULL) {
    FREE_ARRAY(char, chars, length + 1);
    return interned;
  }

Code block 96

c
  return allocateString(chars, length, hash);

Code block 97

c
#include "object.h"

Code block 98

c
#include "table.h"

Code block 99

c
#include "value.h"

Code block 100

c
void tableAddAll(Table* from, Table* to);

Code block 101

c
ObjString* tableFindString(Table* table, const char* chars,
                           int length, uint32_t hash);

Code block 102

text
#endif

Code block 103

c
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

c
    case VAL_NUMBER: return AS_NUMBER(a) == AS_NUMBER(b);

Code block 105

c
    case VAL_OBJ:    return AS_OBJ(a) == AS_OBJ(b);

Code block 106

c
    default:         return false; // Unreachable.

参考资料

← 返回列表
← 上一篇 Strings:clox 的字符串对象与内存管理 下一篇 → Global Variables:声明、读取与 assignment

评论 (0)

暂无评论,来留下第一条吧。
登录 或 注册 后才能发表评论