If you want to benchmark performance, using unit tests’ measure { ... } block is a good starting point, as it runs it a few times and calculates elapsed time, standard deviation, etc.
I’d also suggest:
- testing it with a type where sort is relatively efficient (e.g.
[Int] rather than [String]) so that you focus on sort speed rather than comparison speed);
- do a sort that has observable time (e.g. a large array) and repeating the sort many times; and
- do something simple with the final result so that if you test an optimized build, you don’t risk having it optimize out some code that generates a result that you don’t use.
But for quick performance testing, Xcode unit tests are pretty easy. For example:
class MyAppTests: XCTestCase {
let iterationCount = 1_000
// build large array
var array = (0 ..< 1_000).map { _ in Int.random(in: 0 ..< 1_000_000) }
// test performance
func testSortPerformance() {
measure {
for _ in 0 ..< iterationCount {
let results = array.sorted()
XCTAssert(!results.isEmpty)
}
}
}
func testBubbleSortPerformance() {
measure {
for _ in 0 ..< iterationCount {
let results = array.bubbleSorted()
XCTAssert(!results.isEmpty)
}
}
}
}
That will yield the following results in the Report Navigator:

Or down in the console, you’ll see the details:
/.../MyAppTests.swift:33: Test Case '-[MyAppTests.MyAppTests testBubbleSortPerformance]' measured [Time, seconds] average: 0.603, relative standard deviation: 3.284%, values: [0.613748, 0.580443, 0.590879, 0.586842, 0.626791, 0.610288, 0.595295, 0.588713, 0.594823, 0.647156], performanceMetricID:com.apple.XCTPerformanceMetric_WallClockTime, baselineName: "", baselineAverage: , maxPercentRegression: 10.000%, maxPercentRelativeStandardDeviation: 10.000%, maxRegression: 0.100, maxStandardDeviation: 0.100
/.../MyAppTests.swift:23: Test Case '-[MyAppTests.MyAppTests testSortPerformance]' measured [Time, seconds] average: 0.025, relative standard deviation: 13.393%, values: [0.033849, 0.026869, 0.022752, 0.023048, 0.023024, 0.022847, 0.023286, 0.023987, 0.023803, 0.022640], performanceMetricID:com.apple.XCTPerformanceMetric_WallClockTime, baselineName: "", baselineAverage: , maxPercentRegression: 10.000%, maxPercentRelativeStandardDeviation: 10.000%, maxRegression: 0.100, maxStandardDeviation: 0.100
And, while I’m at it, I’d probably test the sort algorithms themselves, too, e.g. making sure that the results were increasing values and that the total of all the items still added up:
func testBubbleSort() {
let results = array.bubbleSorted()
var previous = results[0]
for index in 1 ..< results.count {
let current = results[index]
XCTAssertLessThanOrEqual(previous, current)
previous = current
}
XCTAssertEqual(results.sum(), array.sum())
}