2

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?

jscs
  • 63,694
  • 13
  • 151
  • 195
Fredrik Johansson
  • 1,301
  • 1
  • 13
  • 26

1 Answers1

3

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.

Richard J. Ross III
  • 55,009
  • 24
  • 135
  • 201
  • 2
    Not only does it make the code hard to read, it bypasses dispatch which can change behavior in many ways. Overall, there is almost **never** a reason to do this. When you think you *might* have a reason to do so, a better solution is almost always to revisit the architecture/algorithm used in the surrounding code. – bbum May 25 '12 at 16:34
  • @bbum: Yes, but I guess that quite often these rewrites mean lower encapsulation, which I think is a shame. – Fredrik Johansson May 25 '12 at 17:17
  • 1
    Agreed; 99% of the time that I've seen IMP caching in use, it has been unnecessary. The reality is that IMP caching, in and of itself, breaks encapsulation (i.e. if you were to install a KVO observer after caching the IMP, you'll have the wrong IMP). – bbum May 25 '12 at 23:53