Runtime

Runtime

IMP Caching

IMP caching is a common optimisation strategy in the hot loop of Objective-C code that uses older Objective-C runtime libraries. Instead of using the [object message:argument] syntax that invokes objc_msgSend() or objc_msgLookup(), the process splits message-sending into two phases:

  1. Use [NSObject methodForSelector:] to retrieve a pointer to the function that implements the method. The return type of this method is IMP.
  2. Call the function via the pointer found in the step 1, with the receiver as the first argument and the method selector as the second argument.

The goal of IMP caching is to perform the first step once on process launch, instead of using the Objective-C runtime to locate the function dynamically every time the process sends the message. In the Apple Objective-C runtime, IMP caching is less relevant because the runtime library maintains its own implementation cache (and invalidates it correctly when the process swizzles methods on classes, or loads categories that override existing methods).