Skip to content

Commit f436764

Browse files
committed
Merge pull request #616 from dduan/removeAll_speedup
[stdlib][performance] skip copying old values during removeAll(keepCapacity: true)
2 parents 16d9766 + b177c69 commit f436764

File tree

1 file changed

+11
-17
lines changed

1 file changed

+11
-17
lines changed

stdlib/public/core/HashedCollections.swift.gyb

Lines changed: 11 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -3394,27 +3394,21 @@ internal enum _Variant${Self}Storage<${TypeParametersDecl}> : _HashStorageType {
33943394
}
33953395
}
33963396

3397-
internal mutating func nativeRemoveAll() {
3398-
var nativeStorage = native
3399-
3400-
// FIXME(performance): if the storage is non-uniquely referenced, we
3401-
// shouldn’t be copying the elements into new storage and then immediately
3402-
// deleting the elements. We should detect that the storage is not uniquely
3403-
// referenced and allocate new empty storage of appropriate capacity.
3397+
internal mutating func nativeKeepCapacityRemoveAll() {
34043398

34053399
// We have already checked for the empty dictionary case, so we will always
34063400
// mutating the dictionary storage. Request unique storage.
3407-
let (reallocated, _) = ensureUniqueNativeStorage(nativeStorage.capacity)
3408-
if reallocated {
3409-
nativeStorage = native
3410-
}
34113401

3412-
for var b = 0; b != nativeStorage.capacity; ++b {
3413-
if nativeStorage.isInitializedEntry(b) {
3414-
nativeStorage.destroyEntryAt(b)
3402+
if !isUniquelyReferenced() {
3403+
self = .Native(NativeStorageOwner(minimumCapacity: native.capacity))
3404+
} else {
3405+
for b in 0..<native.capacity {
3406+
if native.isInitializedEntry(b) {
3407+
native.destroyEntryAt(b)
3408+
}
34153409
}
34163410
}
3417-
nativeStorage.count = 0
3411+
native.count = 0
34183412
}
34193413

34203414
internal mutating func removeAll(keepCapacity keepCapacity: Bool) {
@@ -3428,13 +3422,13 @@ internal enum _Variant${Self}Storage<${TypeParametersDecl}> : _HashStorageType {
34283422
}
34293423

34303424
if _fastPath(guaranteedNative) {
3431-
nativeRemoveAll()
3425+
nativeKeepCapacityRemoveAll()
34323426
return
34333427
}
34343428

34353429
switch self {
34363430
case .Native:
3437-
nativeRemoveAll()
3431+
nativeKeepCapacityRemoveAll()
34383432
case .Cocoa(let cocoaStorage):
34393433
#if _runtime(_ObjC)
34403434
self = .Native(NativeStorage.Owner(minimumCapacity: cocoaStorage.count))

0 commit comments

Comments
 (0)