Why let and var distinction matters in Swift - Performance Analysis
When we use let and var in Swift, it affects how the program runs over time.
We want to see how choosing between constant and variable storage changes the work done as the program runs.
Analyze the time complexity of this Swift code snippet.
func sumNumbers(_ n: Int) -> Int {
let constantValue = 5
var total = 0
for i in 1...n {
total += i + constantValue
}
return total
}
This code adds numbers from 1 to n, each time adding a constant value stored with let.
Look at what repeats as the input grows.
- Primary operation: The
forloop runs through numbers 1 to n. - How many times: Exactly n times, once for each number.
As n grows, the loop runs more times, doing more additions.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 additions |
| 100 | About 100 additions |
| 1000 | About 1000 additions |
Pattern observation: The work grows directly with n, the number of loop steps.
Time Complexity: O(n)
This means the time to run grows in a straight line as the input size increases.
[X] Wrong: "Using let instead of var makes the loop faster."
[OK] Correct: The choice of let or var for constants inside the loop does not change how many times the loop runs or the main work done.
Understanding how constants and variables affect program steps helps you explain code efficiency clearly and confidently.
What if we replaced the constant let constantValue with a variable var constantValue that changes inside the loop? How would the time complexity change?