0

for performance reasons:

does my code perform better if I implement a delegate protocol such that the delegate implements all unused methods as no-op stubs, like this?

@protocol FooDelegate <NSObject>
- (void) requiredFooThing;
@end

....

// a class which implements FooDelegate:
- (void) requiredFooThing { /* does nothing */ };

or is it better to just make the protocol methods optional and use reflection to see if the callee will respond?

@protocol FooDelegate <NSObject>
@optional
- (void) optionalFooThing;
@end

....

// runtime reflection
if([_delegate respondsToSelector:@selector(optionalFooThing)])
{
    [_delegate optionalFooThing];
}

the question is, is the runtime reflection more expensive than sending a message?

4

1 回答 1

0

This is a very subjective question, so depending on your specific use-case, I think a test is in order. But I do recall seeing some posts on the use of KVO as being more expensive that specific subclassing and this question appears to be along a similar vein. I would think reflection would be more expensive than the specific delegate protocol. Keep in mind you can mark delegate methods as @optional/@required. Delegation is also a well established design pattern used extensively throughout. Once again I don't think it's possible to give a specific answer that holds up in all cases.

于 2013-10-22T17:00:26.310 回答