What will be printed by this Swift XCTest performance test?
func testPerformanceExample() { measure { var sum = 0 for i in 1...1000 { sum += i } print(sum) } }
Think about the sum of numbers from 1 to 1000.
The sum of numbers from 1 to 1000 is 500500, so the print inside the measure block outputs 500500.
What is the main purpose of using a measure block in XCTest performance tests?
Think about what performance testing means.
The measure block runs the code multiple times and reports the average execution time to help identify performance issues.
What error will this Swift performance test cause?
func testPerformance() { measure { var array = [1, 2, 3] array.append(4) } }
Look at how the array is declared and what method is called on it.
The array is declared as a constant with let, so calling append which mutates the array causes a compilation error.
Which option shows the correct syntax to measure the performance of sorting an array in XCTest?
Remember the difference between sorted() and sort() methods.
measure is called without parentheses. sorted() returns a sorted array without changing the original. sort() is mutating and returns Void, so option D is wrong.
You run a performance test with this code:
func testPerformance() {
measure {
for _ in 1...1000 {
_ = (1...1000).map { $0 * 2 }
}
}
}The average time reported is unexpectedly high. Which change will most likely improve the accuracy of the performance measurement?
Think about what the measure block repeats and what you want to measure.
Putting the for loop inside measure causes the entire loop to be repeated multiple times, inflating the measured time. Moving the loop outside lets measure time only the inner operation.