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

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

问题描述

计数() 真的算上所有一个PHP数组中的元素,或者是该值缓存的地方,只是检索得到?


解决方案

好了,我们可以看看源:

<一个href=\"https://github.com/php/php-src/blob/PHP-5.3/ext/standard/array.c#L300\"><$p$p>/ext/standard/array.c

<一个href=\"https://github.com/php/php-src/blob/PHP-5.3/ext/standard/array.c#L300\"><$c$c>PHP_FUNCTION(count)调用<一个href=\"https://github.com/php/php-src/blob/PHP-5.3/ext/standard/array.c#L268\"><$c$c>php_count_recursive(),这反过来又来电<一个href=\"https://github.com/php/php-src/blob/PHP-5.3/Zend/zend_hash.c#L1015\"><$c$c>zend_hash_num_elements()对于非递归阵列,它的实现是这样的:

  ZEND_API INT zend_hash_num_elements(常量的HashTable * HT)
{
    IS_CONSISTENT(HT);    回到HT-GT&; nNumOfElements;
}

所以你可以看到,它的 O(1) $模式= COUNT_NORMAL

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

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

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

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