Performance testing helps you check how fast your code runs. Measure blocks let you time specific parts easily.
0
0
Performance testing with measure blocks in Swift
Introduction
You want to see if a function runs quickly enough for your app.
You need to compare two ways of doing the same task to pick the faster one.
You want to catch slow code before users notice it.
You want to track if your code gets slower after changes.
You want to test performance on different devices or conditions.
Syntax
Swift
func testExample() { measure { // code to measure } }
The measure block runs the code inside multiple times to get an average time.
This is used inside XCTest test cases for performance testing.
Examples
This measures how long it takes to sort an array of 1000 numbers.
Swift
func testSortingPerformance() { let array = (1...1000).shuffled() measure { _ = array.sorted() } }
This measures how long it takes to build a string by adding numbers one by one.
Swift
func testStringConcatenation() { measure { var text = "" for i in 1...1000 { text += "\(i)" } } }
Sample Program
This test measures how long it takes to add 10,000 numbers to an array. The measure block runs the code multiple times and shows the average time in Xcode's test results.
Swift
import XCTest final class PerformanceTests: XCTestCase { func testArrayAppendPerformance() { var numbers = [Int]() measure { numbers = [] for i in 1...10000 { numbers.append(i) } } } } // To run this test, use Xcode's test navigator or command+U shortcut.
OutputSuccess
Important Notes
Performance tests run the code several times to get a reliable average.
Use simple code inside measure blocks to get clear results.
Run performance tests on real devices for best accuracy.
Summary
Use measure blocks inside XCTest to check how fast code runs.
They run the code multiple times and report average time.
This helps find slow parts and improve app speed.