Friday, December 31, 2021 [Tweets] [Favorites]

The Surprising Cost of Checking Protocol Conformances in Swift

Noah Martin (Hacker News):

The entry point to our investigation is Mike Ash’s PR which implements a 13x faster cache that was released in Swift 5.4.


We now see that the speed of protocol conformance lookups is dependent on the number of conformances in your app. This will be influenced by how many Swift libraries you link to, and how many conformances you include in your own code. otool -l | | grep _swift5_proto -A 4 tells us Uber’s app has a 411200 byte protocol conformance section. Each 4 bytes is a relative pointer so 411200 / 4 = 102,800 conformances.


One source of low hanging fruit that might be in your app is removing protocols that are used only for providing stub implementations in unit tests. These can be compiled out of release builds of the app to avoid them being included in runtime metadata.


Profiling your app using tools like Instruments or the Emerge startup time visualization can help you identify where conformance checks are most often used in your app. Then you can refactor code to avoid them entirely.


The concept behind zconform is to eagerly load all possible protocol conformances and store them in a map keyed by the protocol’s address in memory.


Update (2022-01-03): Checking protocol conformances can also be a bottleneck in Objective-C.


Stay up-to-date by subscribing to the Comments RSS Feed for this post.

Leave a Comment