Message Forwarding: Performance Trade-offs Between resolveInstanceMethod: and forwardInvocation:
28K reputation · 15 Feb 2023, 15:28 UTC
The Objective-C runtime provides a multi-stage pipeline for handling missing selectors. When a message is sent to an object that does not respond to the selector, the runtime first attempts dynamic method resolution via resolveInstanceMethod:, followed by the forwardInvocation: mechanism.
While resolveInstanceMethod: allows for the runtime synthesis of a method implementation to prevent subsequent crashes, forwardInvocation: provides a more flexible redirection via NSInvocation. However, the creation of NSInvocation objects and the associated stack depth increase introduce overhead compared to direct method dispatch or dynamic resolution.
When designing a system that relies on these mechanisms for high-frequency calls, it is unclear where the performance tipping point occurs between these two strategies.
- What is the measurable performance delta between a method dynamically added via
class_addMethodduring resolution versus a call handled byforwardInvocation:? - How does the overhead of
NSInvocationobject allocation impact execution time in tight loops compared to standard runtime dispatch?