深入for,while,foreach遍历时间比较的详解

yipeiwu_com6年前PHP代码库
这个是从别人空间里看来的,不过自己还真从来没这么做过他们三者之间的比较,今天也学习了一下。
复制代码 代码如下:

<?php
$arr = array();
for($i = 0; $i < 50000; $i++){
$arr[] = $i*rand(1000,9999);
}
function GetRunTime()
{
list($usec,$sec)=explode(" ",microtime());
return ((float)$usec+(float)$sec);
}
/*=============================================*/
$time_start = GetRunTime();
for($i = 0; $i < count($arr); $i++){
$str = $arr[$i];
}
$time_end = GetRunTime();
$time_used = $time_end - $time_start;
echo 'Used time of for:'.round($time_used, 7).'(s)<br /><br />';
unset($str, $time_start, $time_end, $time_used);
/*=============================================*/
$time_start = GetRunTime();
while(list($key, $val) = each($arr)){
$str = $val;
}
$time_end = GetRunTime();
$time_used = $time_end - $time_start;
echo 'Used time of while:'.round($time_used, 7).'(s)<br /><br />';
unset($str, $key, $val, $time_start, $time_end, $time_used);
/*=============================================*/
$time_start = GetRunTime();
foreach($arr as $key => $val){
$str = $val;
}
$time_end = GetRunTime();
$time_used = $time_end - $time_start;
echo 'Used time of foreach:'.round($time_used, 7).'(s)<br /><br />';
?>

相关文章

php用数组返回无限分类的列表数据的代码

复制代码 代码如下: /*—————————————————— */ //– 获取无限分类的列表数据 /*—————————————————— */ function get_sort...

如何写php守护进程(Daemon)

守护进程(Daemon)是运行在后台的一种特殊进程。它独立于控制终端并且周期性地执行某种任务或等待处理某些发生的事件。守护进程是一种很有用的进程。php也可以实现守护进程的功能。 一、基...

php时间函数用法分析

本文实例讲述了php时间函数用法。分享给大家供大家参考,具体如下: php中有unix时间戳的 相关操作函数,使用很方便 time() 返回当前的 Unix 时间戳 microtime...

PHP中常用的转义函数

1. addslashesaddslashes对SQL语句中的特殊字符进行转义操作,包括(‘), (“), (), (NUL)四个字符,此函数在DBMS没有自己的转义函数时候使用,但是如...

php你的验证码安全码?

php你的验证码安全码?

验证码的作用主要有防止暴力破解,防止恶意灌水,防止自动提交等,在这里我就不多说了。验证码的类型也有数字、字母等,甚至厉害点的还有中文的。但是不管你的验证码多么厉害,只要你在表单验证中存在...