Performance testing with measure blocks in Swift - Time & Space Complexity
Performance testing with measure blocks helps us see how long code takes to run as input grows.
We want to know how the running time changes when we test different input sizes.
Analyze the time complexity of the following code snippet.
func sumArray(_ numbers: [Int]) -> Int {
var total = 0
for number in numbers {
total += number
}
return total
}
measure {
_ = sumArray(Array(1...n))
}
This code sums all numbers in an array and measures how long it takes.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each number in the array to add it.
- How many times: Once for every item in the array (n times).
Explain the growth pattern intuitively.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 additions |
| 100 | About 100 additions |
| 1000 | About 1000 additions |
Pattern observation: The work grows directly with the number of items; double the items means double the work.
Time Complexity: O(n)
This means the time to run grows in a straight line with the input size.
[X] Wrong: "The measure block runs instantly no matter the input size."
[OK] Correct: The time depends on how many items we process; bigger inputs take longer.
Knowing how to measure and understand time growth helps you explain your code's speed clearly and confidently.
"What if we changed the sumArray function to sum only half the array? How would the time complexity change?"