对于数组,PHP 的 count() 函数是 O(1) 还是 O(n)? [英] Is PHP's count() function O(1) or O(n) for arrays?

查看:28
本文介绍了对于数组,PHP 的 count() 函数是 O(1) 还是 O(n)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

count() 真的计算所有的PHP 数组的元素,或者该值是否缓存在某处并被检索?

Does count() really count the all the elements of a PHP array, or is this value cached somewhere and just gets retrieved?

推荐答案

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

Well, we can look at the source:

/ext/standard/array.c

PHP_FUNCTION(计数) 调用 php_count_recursive(),它依次调用 zend_hash_num_elements() 用于非递归数组,其实现方式如下:

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;
}

所以你可以看到,对于 $mode = COUNT_NORMAL,它是 O(1).

So you can see, it's O(1) for $mode = COUNT_NORMAL.

这篇关于对于数组,PHP 的 count() 函数是 O(1) 还是 O(n)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆