PHP的count()函数是数组的O(1)还是O(n)?
是否count()真的计算了PHP数组的所有元素,还是将此值缓存在某个地方并被获取?
回答:
好吧,我们可以看看源代码:
[/ext/standard/array.c](https://github.com/php/php-src/blob/PHP-5.3/ext/standard/array.c#L300)PHP_FUNCTION(count)call
php_count_recursive(),这反过来又需要zend_hash_num_elements()非递归数组,该数组是通过以下方式实现的:
ZEND_API int zend_hash_num_elements(const HashTable *ht){
IS_CONSISTENT(ht);
return ht->nNumOfElements;
}
所以你可以看到,它O(1)的$mode = COUNT_NORMAL。
以上是 PHP的count()函数是数组的O(1)还是O(n)? 的全部内容, 来源链接: utcz.com/qa/398113.html


