views:

53

answers:

1

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
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
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
Right. Even with IMP/SEL?
SpecialK
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
Good :) Thanks for your time!
SpecialK