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

问题描述

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


解决方案

好了,我们可以看看源:

<$p$p>/ext/standard/array.c

<$c$c>PHP_FUNCTION(count)调用<$c$c>php_count_recursive(),这反过来又来电<$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)的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-06 06:09