Formatting output in Rust - Time & Space Complexity
When we format output in Rust, we want to know how the time it takes changes as the data grows.
We ask: How does printing or formatting many items affect the program's speed?
Analyze the time complexity of the following code snippet.
fn main() {
let numbers = vec![1, 2, 3, 4, 5];
for num in &numbers {
println!("Number: {}", num);
}
}
This code prints each number in a list with some text formatting.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each number in the list and formatting it for printing.
- How many times: Once for each number in the list (n times).
As the list gets bigger, the program formats and prints more lines.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 formatting and print operations |
| 100 | About 100 formatting and print operations |
| 1000 | About 1000 formatting and print operations |
Pattern observation: The work grows directly with the number of items; double the items, double the work.
Time Complexity: O(n)
This means the time to format and print grows in a straight line with the number of items.
[X] Wrong: "Formatting output is always very fast and does not depend on how many items we print."
[OK] Correct: Each item needs its own formatting and printing step, so more items mean more work and more time.
Understanding how output formatting scales helps you write efficient programs and explain your code clearly in interviews.
"What if we changed the loop to format all numbers into one big string before printing? How would the time complexity change?"