Friday, February 22, 2019

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 for TextStorageSwiftSubclass compared to NSTextStorage. 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 subclass NSTextStorage.

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.

Jonas Boberg:

Note that this is not just an issue with subclasses, but also delegate methods, such as NSLayoutManagerDelegate shouldUseTemporaryAttributes.


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.

Comments RSS · Twitter

Leave a Comment