当前位置: 首页 > 图文教程 > 网络编程 > PHP > PHP 递归效率分析

PHP
PHP新手总结的PHP基础知识
php实现gb2312和unicode间编码转换
用php语言实现数据库连接详细代码介绍
详细解析 PHP 向 MySQL 发送数据过程
利用PHP V5开发多任务应用程序
详细讲解PHP中缓存技术的应用
php escapeshellcmd多字节编码漏洞
《PHP设计模式介绍》导言
《PHP设计模式介绍》第一章 编程惯用法
《PHP设计模式介绍》第二章 值对象模式
《PHP设计模式介绍》第三章 工厂模式
《PHP设计模式介绍》第四章 单件模式
《PHP设计模式介绍》第五章 注册模式
《PHP设计模式介绍》第六章 伪对象模式
《PHP设计模式介绍》第七章 策略模式
《PHP设计模式介绍》第八章 迭代器模式
《PHP设计模式介绍》第九章 观测模式
《PHP设计模式介绍》第十章 规范模式
《PHP设计模式介绍》第十一章 代理模式
《PHP设计模式介绍》第十二章 装饰器模式

PHP 递归效率分析


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2010-01-10   浏览: 138 ::
收藏到网摘: n/a

PHP的递归效率一般认为是低效的。大概一年前,我写了一篇博文,对三种遍历树的方法进行了比较,发现递归算法的效率最低。 而且是差了3倍的效率。所以,PHP中的递归一定要小心的对待。
最近写了一个快速排序的算法,发现PHP中的递归效率不能一刀切,在各种不同的服务器中,可能会表现不一样。
复制代码 代码如下:

function qsort(&$arr)
{
_quick_sort($arr, 0, count($arr) - 1);
}
/**
* 采用递归算法的快速排序。
*
* @param array $arr 要排序的数组
* @param int $low 最低的排序子段
* @param int $high 最高的排序字段
*/
function _quick_sort(&$arr, $low, $high)
{
$low_data = $arr[$low];
$prev_low = $low;
$prev_high = $high;
while ($low < $high)
{
while ($arr[$high] >= $low_data && $low < $high) {
$high--;
}
if ($low < $high) {
$arr[$low] = $arr[$high];
$low++;
}
while ($arr[$low] <= $low_data && $low < $high) {
$low++;
}
if ($low < $high) {
$arr[$high] = $arr[$low];
$high--;
}
}
$arr[$low] = $low_data;
if ($prev_low < $low) {
_quick_sort($arr, $prev_low, $low);
}
if ($low + 1 < $prev_high) {
_quick_sort($arr, $low + 1, $prev_high);
}
}
function quick_sort(&$arr)
{
$stack = array();
array_push($stack, 0);
array_push($stack, count($arr) -1);
while (!empty($stack)) {
$high = array_pop($stack);
$low = array_pop($stack);
$low_data = $arr[$low];
$prev_low = $low;
$prev_high = $high;
while ($low < $high)
{
while ($arr[$high] >= $low_data && $low < $high) {
$high--;
}
if ($low < $high) {
$arr[$low] = $arr[$high];
$low++;
}
while ($arr[$low] <= $low_data && $low < $high) {
$low++;
}
if ($low < $high) {
$arr[$high] = $arr[$low];
$high--;
}
}
$arr[$low] = $low_data;
if ($prev_low < $low) {
array_push($stack, $prev_low);
array_push($stack, $low);
}
if ($low + 1 < $prev_high) {
array_push($stack, $low + 1);
array_push($stack, $prev_high);
}
}
}

下面是测试速度的代码:
复制代码 代码如下:

function qsort_test1()
{
$arr = range(1, 1000);
shuffle($arr);
$arr2 = $arr;
$t1 = microtime(true);
quick_sort($arr2);
$t2 = microtime(true) - $t1;
echo "非递归调用的花费:" . $t2 . "\n";
$arr1 = $arr;
$t1 = microtime(true);
qsort($arr1);
$t2 = microtime(true) - $t1;
echo "递归调用的花费:" . $t2 . "\n";


在我的IIS 服务器上(CGI)模式,我的测试结果是:
非递归调用的花费:0.036401009559631
递归调用的花费:0.053439617156982
在我的Apache 服务器上,我的测试结果是:
非递归调用的花费:0.022789001464844
递归调用的花费:0.014809131622314
结果完全相反,而PHP的版本是一样的。
看来对递归的效率要具体问题具体分析了。