Objective-C: Why check nil before respondsToSelector:?

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.


You are correct. This is technically unnecessary overhead in Obj-C as any message sent to nil will return nil automatically. However, if you ignore the call to respondsToSelector: by first checking if it's nil, then you will skip the overhead of the respondsToSelector: call. So it would be faster, but by how much, I'm not sure.