Skip to content

Commit 7e083cd

Browse files
authored
Optimize removing nonexistent attributes in AttributedString (#1150)
1 parent a293d46 commit 7e083cd

File tree

4 files changed

+14
-2
lines changed

4 files changed

+14
-2
lines changed

Benchmarks/Benchmarks/AttributedString/BenchmarkAttributedString.swift

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -432,6 +432,12 @@ let benchmarks = {
432432
blackHole(hasher.finalize())
433433
}
434434

435+
Benchmark("removeNonExistentAttribute") { benchmark in
436+
var str = manyAttributesString
437+
str.testBool = nil
438+
blackHole(str)
439+
}
440+
435441
struct TestAttribute : AttributedStringKey {
436442
static var name = "0"
437443
typealias Value = Int

Benchmarks/Package.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -88,7 +88,7 @@ switch usePackage {
8888

8989
let package = Package(
9090
name: "benchmarks",
91-
platforms: [.macOS("13.3"), .iOS("16.4"), .tvOS("16.4"), .watchOS("9.4")], // Should match parent project
91+
platforms: [.macOS("15"), .iOS("18"), .tvOS("18"), .watchOS("11")], // Should match parent project
9292
dependencies: packageDependency,
9393
targets: [
9494
.executableTarget(

Sources/FoundationEssentials/AttributedString/AttributedString+Guts.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -391,7 +391,7 @@ extension AttributedString.Guts {
391391
) where K.Value: Sendable {
392392
let utf8Range = unicodeScalarRange(roundingDown: range)._utf8OffsetRange
393393
self.runs(in: utf8Range).updateEach { attributes, range, mutated in
394-
attributes[K.self] = nil
394+
mutated = attributes.removeValue(forKey: K.self)
395395
}
396396
if K.runBoundaries != nil {
397397
self.enforceAttributeConstraintsAfterMutation(

Sources/FoundationEssentials/AttributedString/AttributedStringAttributeStorage.swift

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -216,6 +216,12 @@ extension AttributedString._AttributeStorage {
216216
_attributeModified(attributeName, old: oldValue, new: newValue)
217217
}
218218
}
219+
220+
mutating func removeValue<T: AttributedStringKey>(forKey: T.Type) -> Bool {
221+
let oldValue = self.contents.removeValue(forKey: T.name)
222+
_attributeModified(T.name, old: oldValue, new: nil)
223+
return oldValue != nil
224+
}
219225

220226
internal mutating func mergeIn(_ other: Self, mergePolicy: AttributeMergePolicy = .keepNew) {
221227
for (key, value) in other.contents {

0 commit comments

Comments
 (0)