Do protocols come with any overhead? (ie. obvious benefits aside, do they slow things down?)
+2
A:
From a runtime point of view (and as far as I know), protocols have no impact on performance because the cost of sending a message is the same, whether the instance is referenced by its class or by a conforming protocol.
From a programming point of view, protocols offers a lot of flexibility, especially when you are designing low-coupling API. The Protocol chapter in the Objective-C Programming Guide is pretty comprehensive on the features provided. You might take a look at it.
Laurent Etiemble
2010-05-28 14:19:57
Part of my worry is that a protocol resembles a C++ pure virtual function -- it's a promise that the object being passed will perform certain methods when asked. Callers to such methods don't care how these methods work. As such compilers like gcc or clang will struggle to optimize code that is not present at compile time.
SpecialK
2010-05-31 05:03:12
There is no compile-time optimization when doing message calling in Objective-C, because of the dynamic behavior of the runtime; message dispatching is always resolved at runtime.
Laurent Etiemble
2010-05-31 06:19:44
Right. Even with IMP/SEL?
SpecialK
2010-06-01 04:27:10
At compile time, all the message calls are translated to objc_msgSend (and its siblings).At runtime, when a message is sent with objc_msgSend (or its siblings), the correct implementation is looked up in the global runtime's hash-table (by using the class and the selector). Once the destination implementation (IMP) is known, the call control is passed to it for execution.A selector (SEL), is always resolved at runtime. This allows changes of the implementation at runtime (swizzling, proxying, ...).If you have a reference to an IMP, you can call it as you will do in straight C.
Laurent Etiemble
2010-06-01 06:08:16
Good :) Thanks for your time!
SpecialK
2010-06-02 08:05:52