Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

StructError 堆分配性能基线

硬件:Apple M4 (Mac mini, 2024) 系统:macOS 15, aarch64 Rust:stable 2025-04-30 运行:cargo test --release --test perf_context_allocation -- --nocapture


测试场景

每个场景重复 500,000 次,测量总耗时后计算均值和吞吐量。

场景构造内容
bareStructError::from(UnifiedReason::validation_error())
with-detail同上 + .with_detail("port number out of range")
with-detail+pos同上 + .with_position("src/config.rs:42")
builderbuilder API 等同 with-detail+pos

结果

Before:context: Arc<Vec<OperationContext>>

场景吞吐量ns/iter总耗时
bare28 M/s35.917 ms
with-detail19 M/s53.326 ms
with-detail+pos15 M/s64.632 ms
builder15 M/s65.132 ms

After:context: Option<Arc<Vec<OperationContext>>>

场景吞吐量ns/iter总耗时提升
bare55 M/s18.29 ms+97%
with-detail27 M/s36.618 ms+46%
with-detail+pos20 M/s48.924 ms+32%
builder20 M/s48.824 ms+33%

优化方法

StructErrorImpl 中的 context: Arc<Vec<OperationContext>>context: Option<Arc<Vec<OperationContext>>>

空 context 时不再堆分配,仅在 with_context()ContextAdd::add_context() 首次调用时懒初始化。

分析

  • bare(18.2 ns)现为主要来自 Box::new + 栈构造
  • with-detail 比 bare 多一次 String 堆分配(约 18 ns)
  • with-detail+pos 比 bare 多两次 String 堆分配(约 30 ns)
  • 预期符合:去掉一次空 Arc 堆分配 reduce ~18 ns

测试文件:tests/perf_context_allocation.rs 优化改动:src/core/error/carrier.rs + src/core/report/diagnostic.rs