---
name: rust-performance-optimization
description: "Techniques for optimizing Rust performance, from zero-cost abstractions to profiling."
language: rust
---

# Rust Performance Optimization

Strategies for making Rust applications as fast and efficient as possible.

## Guidelines
- **Leverage zero-cost abstractions**: Use iterators, traits, and generics without fear of runtime overhead.
- **Avoid unnecessary allocations**: Reuse buffers, use `SmallVec` or `ArrayVec` for small collections, and prefer stack allocation.
- **Use efficient data structures**: Choose the right collection (e.g., `HashMap` vs `BTreeMap`) based on the workload.
- **Minimize synchronization overhead**: Use atomics instead of `Mutex` for simple shared state, and minimize lock contention.
- **Inlining and monomorphization**: Trust the compiler's inlining, but use `#[inline]` for small, performance-critical functions.
- **Profile before optimizing**: Use tools like `perf`, `flamegraph`, or `coz` to identify bottlenecks.
- **Parallelize with Rayon**: Use `rayon` for easy data-parallelism on collections.

## Tools & Libraries
- **criterion**: For precise micro-benchmarking.
- **cargo-flamegraph**: For generating flame graphs to visualize performance.
- **perf / heaptrack**: For system-level profiling and memory analysis.
- **rayon**: For high-level parallel programming.

## Trigger Scenarios
- When an application is running slower than expected.
- When optimizing hot loops or performance-critical paths.
- When comparing the efficiency of different algorithms or data structures.
- When a developer asks how to reduce memory usage or CPU cycles.

<!-- synapsis-dsai-managed -->
