Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Here's a small optimisation that may not really be worth the time to implement, and one that I never use personally, but I guess still good to know about. Rather than repeatedly sending the same message to the same object over and over, you can bypass repeated method dispatch by directly using the method implementation. For example, instead of:</p> <pre><code>for (int i = 0; i &lt; 100000000; i++) [someObject messageWithInt:i]; </code></pre> <p>You could try:</p> <pre><code>SEL theSelector = @selector(messageWithInt:); IMP theMethod = [someObject methodForSelector:theSelector]; for (int i = 0; i &lt; 100000000; i++) theMethod (someObject, theSelector, i); </code></pre> <p>This means that the method lookup is only done once and you can invoke the method directly through the returned <code>IMP</code> value. All Objective-C method implementations take at least two arguments, the first argument is the receiving object of type <code>id</code>, which becomes <code>self</code> within the method implementation, and the second argument is the selector [of type <code>SEL</code>] that was used to determine the method implementation, and becomes <code>_cmd</code> in the method implementation.</p> <p>This approach can quickly turn sour if you don't use the correct &ldquo;function definition&rdquo; (I can't remember the proper term). <code>IMP</code> is a <code>typedef</code> for a function that returns <code>void*</code> and takes <code>(id,SEL,...)</code> as arguments. This can make it troublesome to use if the method actually returns something else like <code>float</code>. To help with this matter, you can cast the return value of <code>-methodForSelector:</code>, like this:</p> <pre><code>typedef float (*MyMethodIMP)(id,SEL,int); SEL theSel = @selector(messageWithInt:); MyMethodIMP theMethod = (MyMethodIMP)[someObject methodForSelector:theSel]; float result = 0.0; for (int i = 0; i &lt; 100000000; i++) result += theMethod (someObject, theSel, i); </code></pre> <p>With some care, you can save the <code>theMethod</code> and you may be able to use it for all instances of a particular class, not just one instance, but tread carefully.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload