Variable shadowing in Rust - Time & Space Complexity
Let's explore how variable shadowing affects the time it takes for a program to run.
We want to see if creating new variables with the same name changes how long the code takes as input grows.
Analyze the time complexity of the following code snippet.
fn sum_numbers(numbers: &[i32]) -> i32 {
let mut sum = 0;
for &num in numbers {
let sum = sum + num; // shadowing sum
}
sum
}
This code tries to add all numbers in a list, but it uses variable shadowing inside the loop.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each number in the list.
- How many times: Once for every number in the input list.
Each number in the list is processed once, even with shadowing.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions |
| 100 | 100 additions |
| 1000 | 1000 additions |
Pattern observation: The work grows directly with the number of items; shadowing does not add extra loops.
Time Complexity: O(n)
This means the time to run grows in a straight line with the size of the input list, regardless of shadowing.
[X] Wrong: "Variable shadowing makes the code slower because it creates new variables each time."
[OK] Correct: Shadowing just reuses the name but does not add extra loops or repeated work; it does not increase the number of operations.
Understanding how variable shadowing affects performance shows you can separate naming from actual work done, a useful skill in coding and interviews.
"What if the shadowed variable was used to call a function inside the loop? How would that affect the time complexity?"