Error handling best practices in Rust - Time & Space Complexity
When handling errors in Rust, it's important to know how the program's work grows as it checks and manages errors.
We want to see how error handling affects the time the program takes as input size changes.
Analyze the time complexity of the following Rust code snippet.
fn process_items(items: &[i32]) -> Result {
let mut sum = 0;
for &item in items {
if item < 0 {
return Err("Negative value found".to_string());
}
sum += item;
}
Ok(sum)
}
This code sums a list of numbers but returns an error if any number is negative.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each item in the list once.
- How many times: Once for each item until a negative is found or all are checked.
The program checks each item one by one. If no negative is found early, it checks all items.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 checks |
| 100 | About 100 checks |
| 1000 | About 1000 checks |
Pattern observation: The work grows roughly in direct proportion to the number of items.
Time Complexity: O(n)
This means the time to handle errors grows linearly with the number of items checked.
[X] Wrong: "Error handling always makes the program slower by a lot."
[OK] Correct: In this example, error checks happen as part of normal looping, so the extra cost is small and grows only with input size.
Understanding how error checks affect program speed helps you write clear and efficient Rust code, a skill valued in many coding challenges and real projects.
"What if we changed the error check to happen after the loop instead of during? How would the time complexity change?"