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

最佳答案

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

/ext/standard/array.c

PHP_FUNCTION(count) calls php_count_recursive(), which in turn calls zend_hash_num_elements() for non-recursive array, which is implemented this way:

ZEND_API int zend_hash_num_elements(const HashTable *ht)
{
    IS_CONSISTENT(ht);

    return ht->nNumOfElements;
}

这样就可以看到,它是O(1)$mode = COUNT_NORMAL

关于php - PHP的count()函数是数组的O(1)还是O(n)?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5835241/

10-11 23:04