仅有的幸福2017-05-16 13:00:57
直接說結論:empty 效率最高。
count 需要先統計數組的長度,然後再進行判斷。
有回覆指出此處不正確
之前一直以為count 的時間複雜度是 O(n),這次被打臉後特別去閱讀了一下原碼才發現是實際上是 O(1)。
count源碼連結
count 函數對陣列的運算:
case IS_ARRAY:
RETURN_LONG (php_count_recursive (array, mode TSRMLS_CC) )
走了 php_count_recursive 操作,然後再看 php_count_recursive 函數對陣列的操作是:cnt = zend_hash_num_elements(Z_ARRVAL_P(array));
zend_hash_num_elements 代碼:
ZEND_API int zend_hash_num_elements(HashTable *ht)
{
IS_CONSISTENT(ht);
return ht->nNumOfElements;
}
isset 只能偵測變數是否定義或是否為NULL值。
如果變數有先定義的情況下 !$array 是等效於 empty的。效率也是相等的。
天蓬老师2017-05-16 13:00:57
isset
不能判断我就不回答了,这是PHP基础知识,看手册去
下面主要讲empty
和count
的區別
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之後,兩者之間沒差距(見下文),因為都已經優化了。
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
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