它们大体上执行相同的功能,因此性能差异不应该很大。让我们看一下源代码:
@inlinable
public mutating func removeAll(keepingCapacity keepCapacity: Bool = false) {
if !keepCapacity {
_buffer = _Buffer()
}
else {
self.replaceSubrange(indices, with: EmptyCollection())
}
}
这个方法还有其他几种实现方式,但是模式总是相同的。如果removeAll
参数keepCapacity
为false
,就重新初始化它,基本上等同于说myArray = []
。
所以,唯一的问题就是你是否想保留数组在删除元素后的容量(如果你要清空一个大数组,并且打算用同样大小的另一个数组重新填充它,则可以这样操作)。
如果你愿意,可以进行基准测试。例如,添加“单元测试”目标到你的项目中,将迭代次数增加到足够高,使持续时间可观察:
class MyAppTests: XCTestCase {
func testPerformanceRemoveAll() {
var countTotal = 0
var myArray: [Int] = []
self.measure {
for _ in 0 ..< 1_000_000 {
myArray = Array(repeating: 0, count: 1_000)
myArray.removeAll(keepingCapacity: false)
countTotal += myArray.count
}
}
XCTAssertEqual(countTotal, 0)
}
func testPerformanceReinitialize() {
var countTotal = 0
var myArray: [Int] = []
self.measure {
for _ in 0 ..< 1_000_000 {
myArray = Array(repeating: 0, count: 1_000)
myArray = []
countTotal += myArray.count
}
}
XCTAssertEqual(countTotal, 0)
}
}
有以下结果:
Test Case '-[MyAppTests.MyAppTests testPerformanceReinitialize]' started.
/.../MyApp/MyAppTests/MyAppTests.swift:41: Test Case '-[MyAppTests.MyAppTests testPerformanceReinitialize]' measured [Time, seconds] average: 0.221, relative standard deviation: 6.559%, values: [0.264467, 0.216076, 0.216146, 0.216040, 0.216014, 0.216426, 0.216374, 0.215876, 0.216272, 0.216152], performanceMetricID:com.apple.XCTPerformanceMetric_WallClockTime, baselineName: "", baselineAverage: , maxPercentRegression: 10.000%, maxPercentRelativeStandardDeviation: 10.000%, maxRegression: 0.100, maxStandardDeviation: 0.100
Test Case '-[MyAppTests.MyAppTests testPerformanceReinitialize]' passed (2.646 seconds).
Test Case '-[MyAppTests.MyAppTests testPerformanceRemoveAll]' started.
/.../MyApp/MyAppTests/MyAppTests.swift:26: Test Case '-[MyAppTests.MyAppTests testPerformanceRemoveAll]' measured [Time, seconds] average: 0.235, relative standard deviation: 6.712%, values: [0.282223, 0.229732, 0.229601, 0.229624, 0.229584, 0.229652, 0.229695, 0.229729, 0.229702, 0.229659], performanceMetricID:com.apple.XCTPerformanceMetric_WallClockTime, baselineName: "", baselineAverage: , maxPercentRegression: 10.000%, maxPercentRelativeStandardDeviation: 10.000%, maxRegression: 0.100, maxStandardDeviation: 0.100
Test Case '-[MyAppTests.MyAppTests testPerformanceRemoveAll]' passed (2.602 seconds).
顺便说一下,如果你想知道为什么我在清空数组后添加总数,我只是想确保在清空数组后实际使用它,以确保优化器不会优化掉执行清空操作的代码。虽然在这种情况下并不必要,但是很谨慎。
我也测试了使用 Int
而不是 String
,因为我对 String
的开销不感兴趣,而是想专注于 Array
的行为。
总之,性能差异在很大程度上是无法区分的。