Why Swift for Apple and beyond - Performance Analysis
When we write programs in Swift, it is important to know how fast they run as we give them more work.
We want to understand how the time to finish changes when the input grows bigger.
Analyze the time complexity of the following code snippet.
func printNumbers(_ n: Int) {
for i in 1...n {
print(i)
}
}
printNumbers(5)
This code prints numbers from 1 up to n. It shows how the work grows as n grows.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop that prints each number.
- How many times: It runs exactly n times, once for each number.
Explain the growth pattern intuitively.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 prints |
| 100 | 100 prints |
| 1000 | 1000 prints |
Pattern observation: When n doubles, the work doubles too. The time grows in a straight line with n.
Time Complexity: O(n)
This means the time to finish grows directly with the size of the input.
[X] Wrong: "The loop runs a fixed number of times no matter what."
[OK] Correct: The loop runs as many times as the input number n, so bigger n means more work.
Understanding how loops affect time helps you explain your code clearly and shows you know how programs scale.
"What if we added a nested loop inside the first loop? How would the time complexity change?"