Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective-C: Why check nil before respondsToSelector:?

I've seen code like:

if (delegate != nil && [delegate respondsToSelector:@selector(doSomething)]) ... 

But, sending a message to nil just returns nil (which evaluates to NO), so why not just do:

if ([delegate respondsToSelector:@selector(doSomething)]) ... 

Is the former faster if delegate == nil? Either way, I prefer the latter cause it's less code.

And, less is better than more. Every Unix pro knows that.

like image 796
ma11hew28 Avatar asked Jun 25 '11 17:06

ma11hew28


1 Answers

objc_msgSend, the function used to send dynamic messages in Objective-C immediately checks the first argument (the message receiver) and returns if it == nil. Therefore, the only overhead of nil messaging is a dynamically-linked library function call, which is slightly more costly than an "intra-binary" function call. Overall, is one approach more efficient than the other? Compound conditional statements usually require additional branching, so the answer is indeterminable without looking at the code the compiler generates, but more importantly profiling the running program. Premature optimization is a Bad Thing™, but I congratulate you for actually considering efficiency and questioning "idioms" such as this.

like image 95
Coleman S Avatar answered Sep 17 '22 23:09

Coleman S