Objective-C:为什么在 RespondsToSelector: 之前检查 nil? [英] Objective-C: Why check nil before respondsToSelector:?

查看:115
本文介绍了Objective-C:为什么在 RespondsToSelector: 之前检查 nil?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我见过这样的代码:

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

但是,向 nil 发送消息只会返回 nil(计算结果为 NO),所以为什么不这样做:

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

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

如果delegate == nil,前者会更快吗?不管怎样,我更喜欢后者,因为它的代码更少.

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

而且,lessmore 好.每个 Unix 专业人员都知道这一点.

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

推荐答案

objc_msgSend,Objective-C 中用于发送动态消息的函数会立即检查第一个参数(消息接收者),如果它 == 零.因此,nil 消息传递的唯一开销是动态链接的库函数调用,这比二进制内部"调用稍微贵一些.函数调用.总体而言,一种方法是否比另一种更有效?复合条件语句通常需要额外的分支,因此如果不查看编译器生成的代码,但更重要的是分析正在运行的程序,答案是无法确定的.过早的优化是一件坏事™,但我祝贺你真正考虑效率并质疑习语"比如这个.

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.

这篇关于Objective-C:为什么在 RespondsToSelector: 之前检查 nil?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆