示例工程 09-sequences-and-sparse-arrays

09-sequences-and-sparse-arrays/02-remove-shift-cost/README.md

markdown · 0.7 KB

# 02 · remove-shift-cost
 
**演示**:2000 次头部 `table.remove(t, 1)` vs 尾部 `table.remove(t)`,比较 `os.clock`。
**运行时**:`lua54`、`luajit`。
**运行**:
 
```sh
.tools/bin/lua54 scripts/run-example.lua examples/09-sequences-and-sparse-arrays/02-remove-shift-cost
.tools/bin/lua54 scripts/test-example.lua examples/09-sequences-and-sparse-arrays/02-remove-shift-cost
```
 
**预期输出**(lua 5.4.9 / macOS arm64;耗时随机器变化):
 
```text
head_slower=true
head_empty=true tail_empty=true
```
 
**看点**:头部删除是 O(n),尾部是 O(1),`head_slower=true` 表示头部耗时显著更高。
**注意**:频繁头部删除应改用队列/链表,而不是硬扛。