PHP:函数"count"的复杂度[即O(1),O(n)]是什么? [英] PHP: What is the complexity [i.e O(1),O(n)] of the function 'count'?

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

问题描述

count() 函数的Big-O时间复杂度是多少?用于数组?

What is the Big-O time complexity of the count() function for arrays?

示例

$x = array(1,2,3);
echo count($x); // how many operation does it takes to count the elements 
                // of the array? is it 3, or is it 1

推荐答案

$ time php -r '$a=range(1,1000000); $b=0; for($i=0;$i<10;$i++) $b=count($a);'
real    0m0.458s
$ time php -r '$a=range(1,1000000); $a=array(1); $b=0; for($i=0;$i<10;$i++) $b=count($a);'
real    0m0.457s

对我来说似乎很O(1).

Seems pretty O(1) to me.

经过测试的PHP版本:PHP 5.3.3-1ubuntu9.1 with Suhosin-Patch (cli) (built: Oct 15 2010 14:00:18)

Tested PHP version: PHP 5.3.3-1ubuntu9.1 with Suhosin-Patch (cli) (built: Oct 15 2010 14:00:18)

这篇关于PHP:函数"count"的复杂度[即O(1),O(n)]是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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