Swift Subclass of NSTextStorage Is Slow Because of Swift Bridging
Darren Mo (via Marcin Krzyzanowski):
Calling
-[NSTextStorage attributesAtIndex:effectiveRange:]
is nearly 3 times as slow forTextStorageSwiftSubclass
compared toNSTextStorage
. Time profiling shows that this is caused by the bridging of the Objective-C dictionary return value to Swift. Effectively, this means we cannot use Swift if we want to subclassNSTextStorage
.
There are ways to get around bridging overhead at method call sites. I think the issue here is that these techniques can’t be applied because the subclass is being called by the frameworks. Perhaps there’s a way to work around it by implementing certain methods in Objective-C and others in a Swift extension, but interoperability can be messy depending on how much you are taking advantage of Swift’s features.
Note that this is not just an issue with subclasses, but also delegate methods, such as
NSLayoutManagerDelegate
shouldUseTemporaryAttributes
.
Previously:
- Swift 4: Bridging Peephole for “as” Casts
- Key Difference Between Dictionary and NSDictionary
- Matching and Bridging NSErrors in Swift
- Swift Proposal: Mutability and Foundation Value Types
- Swift Casting With _ObjectiveCBridgeable
Update (2019-02-26): Paul Goracke:
Fortuitously just watched WWDC18 Session 229 (“Using Collections Effectively”) this morning, which raised this concern (and example using NSAttributedString) starting at 28:16.