Optimizing Method Calls

Objective-C’s message-passing implementation of method calls is simple and flexible. What it sacrifices is the speed of a C++-style method call, or of a direct function call.

If you are writing time-critical code, you may want to relinquish the dynamic nature of the Objective-C method call for some extra speed. For example, if your code calls the same method on an object many times in a loop, you may not want to send a dynamic message each time you invoke the method. Objective-C provides a way for you to get a pointer to the function implementing the method, and then call the method via the pointer, bypassing the Objective-C method dispatch process.

Note

If you only call a method once, you should use a standard Objective-C method call. This optimization’s gain in efficiency is directly related to the number of times you invoke the method.

For example, suppose you want to send the following message to invoke a method that takes an integer and has no return value:

[obj 
            methodName:anInt];

You can replace this ordinary Objective-C method call with the following code:

1SEL 
            sel = @selector(methodName:);
2 typedef void (*MpType) (id, SEL, int);
3 MpType 
            mptr = (MpType) [obj methodFor:sel];
4 ...
5 mptr(obj, sel, anInt);

Line 1. Get the selector for the method you want to call. You will use this both to acquire the method pointer and to use it.

Line 2. Define the type of your method pointer. This makes line 3 easier to read. Recall that methods are just C functions with ...

Get Objective-C Pocket Reference now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.