博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
高效中的细节注意
阅读量:4325 次
发布时间:2019-06-06

本文共 1636 字,大约阅读时间需要 5 分钟。

看到yii2.0源码中大量使用

/**     * PHP getter magic method.     * This method is overridden so that attributes and related objects can be accessed like properties.     *     * @param string $name property name     * @throws \yii\base\InvalidParamException if relation name is wrong     * @return mixed property value     * @see getAttribute()     */    public function __get($name)    {        if (isset($this->_attributes[$name]) || array_key_exists($name, $this->_attributes)) {            return $this->_attributes[$name];        } elseif ($this->hasAttribute($name)) {            return null;        } else {            if (isset($this->_related[$name]) || array_key_exists($name, $this->_related)) {                return $this->_related[$name];            }            $value = parent::__get($name);            if ($value instanceof ActiveQueryInterface) {                return $this->_related[$name] = $value->findFor($name, $this);            } else {                return $value;            }        }    }

 其中:

 isset($this->_attributes[$name]) || array_key_exists($name, $this->_attributes) 

这类判断比较多,百思不得其解,翻看官网才得知,

isset()主要判断是否为null,例如 $arr = ['a'=>1, 'b'=>null] ,isset($arr['a']返回true, isset($arr['b'])返回false,

而array_key_exists主要判断键值是否存在,array_key_exists('a', $arr)返回true, array_key_exists('b', $arr)也返回true;

关键是yii2的作者为啥要做两次判断,这次是我疑惑的重点。

个人认为还是出于性能考虑,因为isset效率高于array_key_exists,但同时为保证语句确实是为了到达array_key_exists的作用,

提前做了一次isset()判断,借助比较判断的短路效应,如果isset()为真则说明数组中key必然存在,减少array_key_exists的低效判断,

而isset()为假不一定说明key不存在,有可能是key存在但值是null,所以在用array_key_exists做一次检测,达到效率与效果的平衡。 

转载于:https://www.cnblogs.com/pursuit-happiness/p/4720804.html

你可能感兴趣的文章
【Linux网络编程】使用GDB调试程序
查看>>
feign调用spring clound eureka 注册中心服务
查看>>
ZT:Linux上安装JDK,最准确
查看>>
LimeJS指南3
查看>>
关于C++ const成员的一些细节
查看>>
《代码大全》学习摘要(五)软件构建中的设计(下)
查看>>
C#检测驱动是否安装的问题
查看>>
web-4. 装饰页面的图像
查看>>
微信测试账户
查看>>
Android ListView上拉获取下一页
查看>>
算法练习题
查看>>
学习使用Django一 安装虚拟环境
查看>>
Hibernate视频学习笔记(8)Lazy策略
查看>>
CSS3 结构性伪类选择器(1)
查看>>
IOS 杂笔-14(被人遗忘的owner)
查看>>
自动测试用工具
查看>>
前端基础之BOM和DOM
查看>>
[T-ARA/筷子兄弟][Little Apple]
查看>>
编译Libgdiplus遇到的问题
查看>>
【NOIP 模拟赛】Evensgn 剪树枝 树形dp
查看>>