深入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通过记录IP来防止表单重复提交方法分析

本文实例分析了php通过记录IP来防止表单重复提交方法。分享给大家供大家参考。具体分析如下: 这个原理比较的简单就是用户第一次提交时我们记录提交用户的IP地址,这样如果用户在固定时间内再...

php5 图片验证码实现代码

GD库的函数 1,imagecreatetruecolor -----创建一个真彩色的图像 imagecreatetruecolor(int x_size,int y_size) //x...

高质量PHP代码的50个实用技巧必备(上)

50个高质量PHP代码的实用技巧,希望大家喜欢。 1.不要使用相对路径 常常会看到: require_once('../../lib/some_class.php'); 该...

比较详细PHP生成静态页面教程

一,PHP脚本与动态页面。   PHP脚本是一种服务器端脚本程序,可通过嵌入等方法与HTML文件混合,也可以类,函数封装等形式,以模板的方式对用户请求进行处理。无论以何种方式,它的基本原...

解析php中两种缩放图片的函数,为图片添加水印

有两种改变图像大小的方法.(1):ImageCopyResized() 函数在所有GD版本中有效,但其缩放图像的算法比较粗糙.(2):ImageCopyResampled(),其像素插值...