Home >Backend Development >PHP Tutorial >In-depth explanation of for, while, and foreach traversal time comparison_PHP tutorial

In-depth explanation of for, while, and foreach traversal time comparison_PHP tutorial

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOriginal
2016-07-21 15:08:19934browse

This is seen from other people's space, but I have never done this comparison between the three of them, and I also learned about it today.

Copy code The code is as follows:

$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)

';
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)

';
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)

';
?>

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/327482.htmlTechArticleThis is from someone else’s space, but I have never done this between the three of them. Comparison, I also studied it today. Copy the code The code is as follows: ?php $arr = array(...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn