> One place where useful optimizations could be made are inline functions which take block parameters, since the optimizer is able to improve the inlined code based on the calling code. However, as far as I know, no current blocks-capable compilers perform any of these optimizations, although I haven't investigated it thoroughly.<p>> [...]<p>> for_each is a template function, which means that it gets specialized for this particular type. This makes it an excellent candidate for inlining, and it's likely that an optimizing compiler will end up generating code for the above which would be just as good as the equivalent for loop.<p>This is somewhat unfair, as it seems to reflect the common misconception that (e.g.) C++ sort is faster than C qsort because it uses templates, when in fact qsort would be just as fast if its implementation were written in the .h file, as C++ sort's is. Compilers are perfectly capable of inlining calls to function pointers.<p>Calls to blocks should be able to be inlined too, but I guess they're still a new feature; I did a quick test, and it seems that gcc cannot inline them, but llvm-gcc and clang can.<p>In this case, the article suggests:<p><pre><code> [array do:^(id obj) {
NSLog(@"Obj is %@", obj);
}];
</code></pre>
Objective-C message calls are never inlined since they are dynamic, but if you write something like:<p><pre><code> static void for_each(NSArray *array, void (^callback)(id)) {
for(id obj in array) {
callback(obj);
}
}
[...]
for_each(array, ^(id obj){ NSLog(@"%@", obj); });
</code></pre>
llvm-gcc and clang are able to generate code equivalent to doing the for loop directly.