Search code examples
objective-cmessageprebinding

Pre-binding message to avoid method lookup


This article http://www.gnustep.org/resources/ObjCFun.html states that

Anywhere that time is critical, it's possible in Objective-C to pre-bind a message to its implementation, thus avoiding the expensive message lookup.

How do you do this pre-binding? This is not about selectors, is it?


Solution

  • It involves implementations. Consider the following (+1 internets if you get the reference):

    NSArray *myReallyLongArrayOf1000items;
    
    for (int i = 0; i < 1000; i++)
        NSLog(@"%@", [myReallyLongArrayOf1000items objectAtIndex:i]);
    

    It takes time for the obj-c runtime to look up exactly how to perform the -objectAtIndex: task. Thus, when we change the block of code to this:

    NSArray *myReallyLongArrayOf1000items;
    
    id (*objectAtIndex)(NSArray *, SEL, int) = (typeof(objectAtIndex)) [myReallyLongArrayOf1000items methodForSelector:@selector(objectAtIndex:)];
    
    for (int i = 0; i < 1000; i++)
        NSLog(@"%@", objectAtIndex(myReallyLongArrayOf1000items, @selector(objectAtIndex:), i);
    

    This uses a C function-pointer, which is much faster than a dynamic look up with objective-c, as it simply calls the method, and does no extra runtime code.

    On the downside, this quickly makes code hard to read, so use this sparingly, if at all.