0
0
Swiftprogramming~5 mins

Performance testing with measure blocks in Swift - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Performance testing with measure blocks
O(n)
Understanding Time 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.

Scenario Under Consideration

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 Repeating Operations

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).
How Execution Grows With Input

Explain the growth pattern intuitively.

Input Size (n)Approx. Operations
10About 10 additions
100About 100 additions
1000About 1000 additions

Pattern observation: The work grows directly with the number of items; double the items means double the work.

Final Time Complexity

Time Complexity: O(n)

This means the time to run grows in a straight line with the input size.

Common Mistake

[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.

Interview Connect

Knowing how to measure and understand time growth helps you explain your code's speed clearly and confidently.

Self-Check

"What if we changed the sumArray function to sum only half the array? How would the time complexity change?"