Time complexity
Time complexity describes how the work of an algorithm grows with the input size n. Rust does not change the math: a nested loop over n elements is still O(n²), even when the types are fancy.
Detailed Explanation
Big-O is a count of steps as a function of n, ignoring constants. One pass over a slice is O(n). A binary search is O(log n). Sorting with sort is O(n log n). Inserting at the front of a Vec is O(n). Hash-map lookup is average O(1) and worst-case O(n).
Rust's type system makes some costs visible. clone() on a String is O(length), not O(1). to_vec() is O(n). Moving a Vec is O(1) — you copy three words. Moving a [u8; 1024] is O(1024). Copy types hide a memcpy in an assignment; that memcpy is cheap for an i32 and measurable for a 4 KiB array. Read the signature: if it takes &[T] and returns Vec<T>, someone allocated and copied.
Amortised costs matter for Vec::push and HashMap::insert. A single call can reallocate the whole table, so it is O(n) that time and O(1) on average. In a real-time loop you reserve up front so the spike cannot happen.
Asymptotics do not replace measurement. An O(n) iterator chain that allocates three intermediate Vecs can lose to a clear for loop. An O(n log n) sort on 20 integers is noise. The method is: pick the right class of algorithm (do not use a quadratic scan for a membership test on a million keys), then profile if it is hot.
When you reason about time: name n, name the operation you count (comparisons, hashes, allocations), and say whether you mean worst, average, or amortised. When you report a number: use a release build. Dev builds lie by a factor of ten or more.
Code Examples
fn contains_naive(xs: &[u32], target: u32) -> bool {
xs.iter().any(|x| *x == target) // O(n)
}
fn main() {
let xs: Vec<u32> = (0..8).collect();
println!("{}", contains_naive(&xs, 3)); // prints: true
println!("{}", xs.binary_search(&3).is_ok()); // prints: true — O(log n), needs sorted
}Common Gotchas
Debug builds are not evidence
Overflow checks and missing optimisation can make an O(n) look like a disaster. Benchmark with `--release`.
Amortised is not per-call
The push that doubles a 10 million element `Vec` is a real pause. `reserve` when you know n.
Clone is not O(1) for owned buffers
`v.clone()` copies every element. `Arc::clone` is O(1). Read the type.
Iterator adapters are usually one pass
`filter` then `map` then `count` is O(n), not O(3n) of separate walks, after fusion.