rust-optimise

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Rust Optimise Best Practices

Rust性能优化最佳实践

Performance optimization guide for Rust applications. Contains 42 rules across 8 categories, prioritized by impact from critical (memory allocation, ownership) to incremental (micro-optimizations).
这是一份Rust应用的性能优化指南,包含8个类别共42条规则,按影响优先级排序,从关键优化(内存分配、所有权)到增量优化(微优化)依次排列。

When to Apply

适用场景

  • Optimizing Rust code for performance or reducing allocations
  • Choosing data structures for optimal algorithmic complexity
  • Working with iterators to avoid unnecessary intermediate allocations
  • Writing async code with Tokio or other runtimes
  • Profiling hot paths and eliminating performance bottlenecks
  • Reviewing code for performance anti-patterns
  • 优化Rust代码性能或减少内存分配
  • 选择最优数据结构以降低算法复杂度
  • 使用迭代器避免不必要的中间内存分配
  • 基于Tokio或其他运行时编写异步代码
  • 分析热点路径并消除性能瓶颈
  • 检查代码中的性能反模式

Rule Categories by Priority

按优先级排序的规则类别

PriorityCategoryImpactPrefix
1Memory AllocationCRITICAL
mem-
2Ownership & BorrowingCRITICAL
own-
3Data Structure SelectionHIGH
ds-
4Iterator & Collection PatternsHIGH
iter-
5Async & ConcurrencyMEDIUM-HIGH
async-
6Algorithm ComplexityMEDIUM
algo-
7Compile-Time OptimizationMEDIUM
comp-
8Micro-optimizationsLOW
micro-
优先级类别影响程度前缀
1内存分配关键
mem-
2所有权与借用关键
own-
3数据结构选择
ds-
4迭代器与集合模式
iter-
5异步与并发中高
async-
6算法复杂度
algo-
7编译时优化
comp-
8微优化
micro-

Quick Reference

快速参考

1. Memory Allocation (CRITICAL)

1. 内存分配(关键)

  • mem-avoid-unnecessary-clone
    - Avoid unnecessary clone calls
  • mem-preallocate-vec-capacity
    - Preallocate Vec capacity
  • mem-use-cow-for-conditional-ownership
    - Use Cow for conditional ownership
  • mem-use-arc-for-shared-immutable-data
    - Use Arc for shared immutable data
  • mem-avoid-format-for-simple-concatenation
    - Avoid format! for simple concatenation
  • mem-use-smallvec-for-small-collections
    - Use SmallVec for small collections
  • mem-avoid-unnecessary-clone
    - 避免不必要的clone调用
  • mem-preallocate-vec-capacity
    - 预分配Vec容量
  • mem-use-cow-for-conditional-ownership
    - 使用Cow实现条件性所有权
  • mem-use-arc-for-shared-immutable-data
    - 使用Arc共享不可变数据
  • mem-avoid-format-for-simple-concatenation
    - 简单字符串拼接避免使用format!
  • mem-use-smallvec-for-small-collections
    - 小型集合使用SmallVec

2. Ownership & Borrowing (CRITICAL)

2. 所有权与借用(关键)

  • own-accept-str-slice-not-string
    - Accept &str instead of &String
  • own-accept-slice-not-vec
    - Accept &[T] instead of &Vec<T>
  • own-use-into-for-flexible-ownership
    - Use Into<T> for flexible ownership
  • own-return-borrowed-when-possible
    - Return borrowed data when possible
  • own-use-asref-for-generic-borrows
    - Use AsRef<T> for generic borrows
  • own-accept-str-slice-not-string
    - 参数接受&str而非&String
  • own-accept-slice-not-vec
    - 参数接受&[T]而非&Vec<T>
  • own-use-into-for-flexible-ownership
    - 使用Into<T>实现灵活的所有权转换
  • own-return-borrowed-when-possible
    - 尽可能返回借用的数据
  • own-use-asref-for-generic-borrows
    - 使用AsRef<T>实现通用借用

3. Data Structure Selection (HIGH)

3. 数据结构选择(高)

  • ds-use-hashset-for-membership
    - Use HashSet for membership tests
  • ds-use-hashmap-for-key-lookup
    - Use HashMap for key-value lookups
  • ds-use-btreemap-for-sorted-iteration
    - Use BTreeMap for sorted iteration
  • ds-use-vecdeque-for-queue-operations
    - Use VecDeque for queue operations
  • ds-use-entry-api-for-conditional-insert
    - Use Entry API for conditional insert
  • ds-use-hashset-for-membership
    - 成员测试使用HashSet
  • ds-use-hashmap-for-key-lookup
    - 键值对查找使用HashMap
  • ds-use-btreemap-for-sorted-iteration
    - 有序迭代使用BTreeMap
  • ds-use-vecdeque-for-queue-operations
    - 队列操作使用VecDeque
  • ds-use-entry-api-for-conditional-insert
    - 条件插入使用Entry API

4. Iterator & Collection Patterns (HIGH)

4. 迭代器与集合模式(高)

  • iter-chain-instead-of-intermediate-collect
    - Chain iterators instead of intermediate collect
  • iter-use-iter-over-into-iter-when-borrowing
    - Use iter() over into_iter() when borrowing
  • iter-use-filter-map-for-combined-operations
    - Use filter_map for combined operations
  • iter-use-flat-map-for-nested-iteration
    - Use flat_map for nested iteration
  • iter-use-extend-for-bulk-append
    - Use extend() for bulk append
  • iter-use-fold-for-accumulation
    - Use fold() for complex accumulation
  • iter-chain-instead-of-intermediate-collect
    - 链式调用迭代器而非中间collect
  • iter-use-iter-over-into-iter-when-borrowing
    - 借用场景使用iter()而非into_iter()
  • iter-use-filter-map-for-combined-operations
    - 组合过滤与映射使用filter_map
  • iter-use-flat-map-for-nested-iteration
    - 嵌套迭代使用flat_map
  • iter-use-extend-for-bulk-append
    - 批量追加使用extend()
  • iter-use-fold-for-accumulation
    - 复杂累加使用fold()

5. Async & Concurrency (MEDIUM-HIGH)

5. 异步与并发(中高)

  • async-avoid-blocking-in-async-context
    - Avoid blocking in async context
  • async-use-join-for-concurrent-futures
    - Use join! for concurrent futures
  • async-use-rwlock-over-mutex-for-read-heavy
    - Use RwLock over Mutex for read-heavy
  • async-minimize-lock-scope
    - Minimize lock scope
  • async-use-buffered-for-bounded-concurrency
    - Use buffered() for bounded concurrency
  • async-avoid-holding-lock-across-await
    - Avoid holding lock across await
  • async-avoid-blocking-in-async-context
    - 异步上下文避免阻塞操作
  • async-use-join-for-concurrent-futures
    - 并发执行Future使用join!
  • async-use-rwlock-over-mutex-for-read-heavy
    - 读密集场景使用RwLock而非Mutex
  • async-minimize-lock-scope
    - 最小化锁的作用域
  • async-use-buffered-for-bounded-concurrency
    - 有界并发使用buffered()
  • async-avoid-holding-lock-across-await
    - await期间避免持有锁

6. Algorithm Complexity (MEDIUM)

6. 算法复杂度(中)

  • algo-avoid-nested-loops-for-lookup
    - Avoid nested loops for lookups
  • algo-use-binary-search-for-sorted-data
    - Use binary search for sorted data
  • algo-use-sort-unstable-when-order-irrelevant
    - Use sort_unstable when order irrelevant
  • algo-use-select-nth-unstable-for-partial-sort
    - Use select_nth_unstable for partial sort
  • algo-use-chunks-for-batch-processing
    - Use chunks() for batch processing
  • algo-avoid-nested-loops-for-lookup
    - 查找操作避免嵌套循环
  • algo-use-binary-search-for-sorted-data
    - 有序数据使用二分查找
  • algo-use-sort-unstable-when-order-irrelevant
    - 无需稳定排序时使用sort_unstable
  • algo-use-select-nth-unstable-for-partial-sort
    - 部分排序使用select_nth_unstable
  • algo-use-chunks-for-batch-processing
    - 批量处理使用chunks()

7. Compile-Time Optimization (MEDIUM)

7. 编译时优化(中)

  • comp-use-const-for-compile-time-computation
    - Use const for compile-time computation
  • comp-prefer-static-dispatch
    - Prefer static dispatch over dynamic
  • comp-reduce-monomorphization-bloat
    - Reduce monomorphization bloat
  • comp-use-const-generics-for-array-sizes
    - Use const generics for array sizes
  • comp-avoid-repeated-parsing-of-static-data
    - Avoid repeated parsing of static data
  • comp-use-const-for-compile-time-computation
    - 编译时计算使用const
  • comp-prefer-static-dispatch
    - 优先使用静态分发而非动态分发
  • comp-reduce-monomorphization-bloat
    - 减少单态化膨胀
  • comp-use-const-generics-for-array-sizes
    - 数组大小使用const泛型
  • comp-avoid-repeated-parsing-of-static-data
    - 避免重复解析静态数据

8. Micro-optimizations (LOW)

8. 微优化(低)

  • micro-use-inline-for-small-functions
    - Apply inline attribute to small hot functions
  • micro-avoid-bounds-checks-in-hot-loops
    - Avoid bounds checks in hot loops
  • micro-use-wrapping-arithmetic-when-safe
    - Use wrapping arithmetic when safe
  • micro-use-byte-literals-for-ascii
    - Use byte literals for ASCII
  • micro-use-inline-for-small-functions
    - 热点小函数添加inline属性
  • micro-avoid-bounds-checks-in-hot-loops
    - 热点循环中避免边界检查
  • micro-use-wrapping-arithmetic-when-safe
    - 安全场景使用包装算术
  • micro-use-byte-literals-for-ascii
    - ASCII字符使用字节字面量

References

参考资料

Related Skills

相关技能

  • For idiomatic patterns, architecture, and code organization, see
    rust-refactor
    skill
  • 如需了解惯用模式、架构与代码组织,请参考
    rust-refactor
    技能