Thursday, May 20, 2021

Preventing Surprisingly Large Objective-C Type Encodings

Peter Steinberger:

If you’re familiar with Objective-C, you likely know about selectors, but they only contain the name and number of parameters. The type each parameter has is stored in the method type encoding, which is encoded as a simple string. With C++ types, those strings can easily become lengthy and add to your binary size. […] Before it was changed, the worst offending method type signature in our codebase contained 13,126 characters. That’s 12 KB (!) for one type.


While you can use strings | grep -e '{' in your app binary to find encodings, it’s not always easy to see the method or variable referenced. So instead, I wrote a helper in Swift to find the largest type encodings of methods and instance variables.


There are various ways you can hide C++ objects. For most situations, I created a separate struct in the ObjC class implementation and moved C++ objects into it. This newly created struct is connected to the class via a unique_ptr. This is an additional level of indirection, but it can be cached before entering any hot paths, so it shouldn’t have any performance drawbacks (see below).


Update (2021-06-05): Peter Steinberger:

Looks like this was picked up and fixed!

“[ObjC] Encode pointers to C++ classes as "^v" if the encoded string would otherwise include template specialization types”

Comments RSS · Twitter

Leave a Comment