Reducing Objective C Message Overhead

This article discusses ways to reduce Objective C performance overhead.
Q: My Objective-C messages take too long compared with C function calls. What can I do?

A: We have chosen to pay a certain performance cost in exchange for the benefits of object-oriented programming. What is really important is to amortize the added overhead of a message send over the cost of running your program. The cost of writing and maintaining correct code is also a consideration.

There is a way to optimize tight loops in code. The methodForSelector: method returns a pointer to the actual C function used to implement a method. This can be used at the beginning of a tight loop to cache the call. For example:

IMP func;

func = [anObject methodForSelector:aSelector];
while (loopingTightly) {
   ...
   func(anObject, @selector(aSelector), args ...);
   ...
}

As long as does not change its value in the inner loop, this technique does not sacrifice any of the advantages of Objective-C (e.g., dynamic binding) and is just as efficient as normal C. Be careful when using this method with methods which pass C types as arguments or expect them as return values; because of the lack of a prototype, non-object variables may be handled incorrectly. See the NSObject class documentation for a full discussion of this problem and its workaround.
Published Date: Feb 20, 2012