Skip to content

[Optimization] skip copying old values during Set's removeAll() #477

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 22 additions & 14 deletions stdlib/public/core/HashedCollections.swift.gyb
Original file line number Diff line number Diff line change
Expand Up @@ -575,6 +575,13 @@ public struct Set<Element : Hashable> :
public mutating func intersectInPlace<
S : SequenceType where S.Generator.Element == Element
>(sequence: S) {
if let other = sequence as? Set<Element> {
// removeAll() is fast, prefer using it when possible
if other.isEmpty {
removeAll()
}
}

// Because `intersect` needs to both modify and iterate over
// the left-hand side, the index may become invalidated during
// traversal so an intermediate set must be created.
Expand Down Expand Up @@ -3394,26 +3401,27 @@ internal enum _Variant${Self}Storage<${TypeParametersDecl}> : _HashStorageType {
}

internal mutating func nativeRemoveAll() {
var nativeStorage = native

// FIXME(performance): if the storage is non-uniquely referenced, we
// shouldn’t be copying the elements into new storage and then immediately
// deleting the elements. We should detect that the storage is not uniquely
// referenced and allocate new empty storage of appropriate capacity.

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

for var b = 0; b != nativeStorage.capacity; ++b {
if nativeStorage.isInitializedEntry(b) {
nativeStorage.destroyEntryAt(b)
if !isUniquelyReferenced() {
switch self {
case .Native(let owner):
owner.deinitializeHeapBufferBridged()
case .Cocoa:
_sanityCheckFailure("internal error: not backed by native storage")
}
let newNativeOwner = NativeStorageOwner(minimumCapacity: native.capacity)
self = .Native(newNativeOwner)
} else {
for b in 0..<native.capacity {
if native.isInitializedEntry(b) {
native.destroyEntryAt(b)
}
}
}
nativeStorage.count = 0
native.count = 0
}

internal mutating func removeAll(keepCapacity keepCapacity: Bool) {
Expand Down