小编典典

PHP的count()函数是数组的O(1)还是O(n)?

php

是否count()真的计算了PHP数组的所有元素,还是将此值缓存在某个地方并被获取?


阅读 365

收藏
2020-05-29

共1个答案

小编典典

好吧,我们可以看看源代码:

[/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

2020-05-29