# Rust 排序：缓存键为何胜过迭代器？

Original title: Matching Puzzle Pieces and Disappointing Benchmarks

> Hacker News story 49554848 · language: zh · submitted 2026-09-03
> Web version: https://zeli.app/zh/story/49554848
> About this feed: https://zeli.app/llms.txt · Agent guide: https://zeli.app/skill.md

▲ 6 · by [speckx](<https://news.ycombinator.com/user?id=speckx>) · 💬 0
[original](<https://llogiq.github.io/2026/03/20/case.html>) · [HN discussion](<https://news.ycombinator.com/item?id=49554848>)

## Summary

最近在 Rust 中处理文本排序时，我纠结于两种方案：是使用 sort_by_cached_key 配合 to_lowercase 分配内存，还是通过迭代器逐字符转换以避免分配。直觉告诉我，避免分配应该更快，毕竟很多字符串的前几个字符就不同。于是，我编写了基准测试，对比了 sort_by_cached_key、手动迭代器方案以及 unicase 库。结果令人意外：除非只处理单个元素，否则 sort_by_cached_key 性能更优。更让人惊讶的是，逐字符迭代进行大小写转换比预想中慢得多，完全抵消了不分配内存的优势。而 unicase 库在增加比较复杂度的情况下，往往表现更佳。

## Key quote

> 真正的惊喜在于，Unicase 库尽管让比较逻辑变得更复杂，却经常能跑得更快。

---

## Cite

- Page: https://zeli.app/zh/story/49554848
- Date: 2026-09-03
- Source: llogiq.github.io (https://llogiq.github.io/2026/03/20/case.html)
- Hacker News: https://news.ycombinator.com/item?id=49554848

## Other languages

- en: https://zeli.app/story/49554848 · markdown: https://zeli.app/story/49554848.md
- ja: https://zeli.app/ja/story/49554848 · markdown: https://zeli.app/ja/story/49554848.md
- ko: https://zeli.app/ko/story/49554848 · markdown: https://zeli.app/ko/story/49554848.md
- de: https://zeli.app/de/story/49554848 · markdown: https://zeli.app/de/story/49554848.md
- es: https://zeli.app/es/story/49554848 · markdown: https://zeli.app/es/story/49554848.md
- ru: https://zeli.app/ru/story/49554848 · markdown: https://zeli.app/ru/story/49554848.md
