🦀 Rust Advanced

What are Rust performance optimization techniques?

Answer

Key Rust performance techniques: Avoid unnecessary allocations — prefer stack-allocated types, use &str over String, reuse Vec buffers with clear() + extend(). Use iterators over index loops — the optimizer handles iterator chains better. Profile before optimizing — use cargo flamegraph or perf to find actual bottlenecks. SIMD — use std::simd (nightly) or the packed_simd / wide crates for data-parallel operations (process 8 floats at once with AVX). Profile-Guided Optimization (PGO): build with instrumentation, run workloads, rebuild using the profile data — LLVM optimizes hot paths. LTO (Link-Time Optimization): set lto = true in Cargo.toml release profile — enables inlining across crate boundaries. Avoid dynamic dispatch — prefer generics over dyn Trait in hot paths to allow inlining. Use Cow<'a, str> for borrowed-or-owned flexibility without always allocating.