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
isset不能判斷數組是不是為空
另外兩個:http://stackoverflow.com/ques...
結論是empty比count有效率
直接說結論:empty 效率最高。
count 需要先統計數組的長度,然後再進行判斷。count源碼連結
count 函數對陣列的運算:
走了 php_count_recursive 操作,然後再看 php_count_recursive 函數對陣列的操作是:
cnt = zend_hash_num_elements(Z_ARRVAL_P(array));
zend_hash_num_elements 代碼:
isset 只能偵測變數是否定義或是否為NULL值。
如果變數有先定義的情況下 !$array 是等效於 empty的。效率也是相等的。
isset
不能判断我就不回答了,这是PHP基础知识,看手册去下面主要讲
empty
和count
的區別根據PHP的源碼(PHP5.4)
在實作中,不論是
empty
,还是count
,都是取的zVal - value
指向的HashTable
结构中的elem_num
結論
所以兩者之間的判斷方式是沒任何差距的,
empty
就是执行了elem_num <= 0
,既然兩者都是執行相同底層程式碼,但是不代表執行速度一樣。速度差異
根據http://stackoverflow.com/ques...中的測試結果來看(測試結果在下方),大家會發現
count
的确要比empty
慢一点,也许大家会疑惑,既然都是判断的elem_num
,那為什麼會慢?為什麼慢
所以結果很明顯了:
count
是函数,empty
却是一个语言构造器
既然是
语言构造器
,那执行效率是肯定比函数高的,比如echo
也是语言构造器
,例如
echo 'str1','str2';
的效率就比echo 'str1'.'str2';
高,更不用说print
了但是,使用OpCache或JIT之後,兩者之間沒差距(見下文),因為都已經優化了。
原生PHP
使用了JIT(或 HipHop VM)
首先 如果不是關聯數組的話 isset 效率高 通常都是使用 empty