Performance Basics
10 examples to get you started with Performance - 7 basic and 3 intermediate.
Busca en todas las páginas de la documentación
10 examples to get you started with Performance - 7 basic and 3 intermediate.
cargo build --releaseProfile or benchmark before changing code.
cargo build --release
cargo bench # if Criterion benches exist
# or: perf record / samply for whole-process profilesRelated: Benchmarking & Profiling
Ship with optimized binaries.
[profile.release]
opt-level = 3
lto = "thin"cargo run --releaseopt-level = 3 enables LLVM optimizationsRelated: Release Tuning
Iterators and generics compile to tight loops.
let sum: u64 = (0..1_000_000).map(|x| x as u64).sum();cargo asm or godbolt if unsureRelated: Zero-Cost Abstractions
Stack and reuse beat heap churn.
let mut buf = String::with_capacity(256);
buf.clear(); // reuse in loopwith_capacity prevents repeated realloc&str over String when borrowing sufficesclone() in hot loopscargo clippy flags redundant clonesRelated: Understanding Allocations
Ownership copies are explicit and costly.
fn process(items: &[Item]) {
for item in items {
use_item(item);
}
}&T and &[T] avoid deep copiesCow<'_, str> when rare mutation neededRelated: Avoiding Clones
Pick structures for access patterns.
use std::collections::HashMap;
let mut index: HashMap<u64, User> = HashMap::with_capacity(1024);Vec for sequential accessHashMap/BTreeMap for lookupsVecDeque for queue patternswith_capacity when size known#[inline] helps cross-crate hot paths.
#[inline]
pub fn cheap_op(x: u32) -> u32 {
x.wrapping_mul(31)
}#[inline] on public tiny helpers in libsOrder fields for locality.
#[repr(C)]
struct Particle {
x: f32,
y: f32,
active: bool,
}repr(C) for predictable layout with FFIRelated: Memory Layout & Cache
Let LLVM vectorize or use explicit SIMD.
let sum: u32 = data.iter().copied().sum();-O3std::simd for hand-tuned kernelsRelated: SIMD & Vectorization
Tune for deploy constraints.
[profile.release]
opt-level = "z"
strip = "symbols"Related: Reducing Binary Size
Stack versions: This page was written for Rust 1.97.0 (edition 2024), Tokio 1.x, Axum 0.8, serde 1.0, sqlx 0.8, clap 4, and Polars 0.46+.
Revisado por Chris St. John·Última actualización: 16 jul 2026