php判断数组是否存为空,php判断数组是否为空 哪个效率高

isset不能判断我就不回答了,这是PHP基础知识,看手册去

下面主要讲empty和count的区别

根据PHP的源代码(PHP5.4)

typedef struct _HashTable

{

int size;

int elem_num;

Bucket** buckets;

} HashTable;

在实现中,不论是empty,还是count,都是取的zVal - value指向的HashTable结构中的elem_num

其它答案中的,说count需要计算长度,拜托,PHP会那么傻?还傻乎乎的跑一遍链表,count会直接返回数组的elem_num

结论

所以两者之间的判断方式是没任何差距的,empty就是执行了elem_num <= 0,既然两者都是执行相同底层代码,但是不代表执行速度一样。

速度差异

根据http://stackoverflow.com/ques...中的测试结果来看(测试结果在下方),大家会发现count的确要比empty慢一点,也许大家会疑惑,既然都是判断的elem_num,那么为什么会慢?

为什么慢

根据PHP的手册:

对empty的解释有一行:

因为是一个语言构造器而不是一个函数,不能被 可变函数 调用。

所以结果很明显了:count是函数,empty却是一个语言构造器

既然是语言构造器,那执行效率是肯定比函数高的,比如echo也是语言构造器,

比如 echo 'str1','str2';的效率就比 echo 'str1'.'str2';高,更不用说print了

但是,使用OpCache或者JIT之后,两者之间没差距(见下文),因为都已经优化了。

原生PHP

Empty empty() 0.118691

Empty count() 0.218974

Full empty() 0.133747

Full count() 0.216424

IF empty empty() 0.166474

IF empty count() 0.235922

IF full empty() 0.120642

IF full count() 0.248273

OR empty empty() 0.123875

OR empty count() 0.258665

OR full empty() 0.157839

OR full count() 0.224869

IF/ELSE empty empty() 0.167004

IF/ELSE empty count() 0.263351

IF/ELSE full empty() 0.145794

IF/ELSE full count() 0.248425

( ? : ) empty empty() 0.169487

( ? : ) empty count() 0.265701

( ? : ) full empty() 0.149847

( ? : ) full count() 0.252891

使用了JIT(或 HipHop VM)

Empty empty() 0.210652

Empty count() 0.212123

Full empty() 0.206016

Full count() 0.204722

IF empty empty() 0.227852

IF empty count() 0.219821

IF full empty() 0.220823

IF full count() 0.221397

OR empty empty() 0.218813

OR empty count() 0.220105

OR full empty() 0.229118

OR full count() 0.221787

IF/ELSE empty empty() 0.221499

IF/ELSE empty count() 0.221274

IF/ELSE full empty() 0.221879

IF/ELSE full count() 0.228737

( ? : ) empty empty() 0.224143

( ? : ) empty count() 0.222459

( ? : ) full empty() 0.221606

( ? : ) full count() 0.231288

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值