XuLaLa.Tech

首页客户端下载Windows 使用V2Ray 教程SSR 教程Clash 教程

PHP FOR vs FOREACH性能比较

2025.04.09

“foreach”比“for”慢。foreach复制需要执行迭代的数组。为了提高性能,需要使用引用的概念。除此之外,“foreach”也很容易使用。

例子

<?php
$my_arr = array();
for ($i = 0; $i < 10000; $i++) {
$my_arr[] = $i;
}
$start = microtime(true);
foreach ($my_arr as $k => $v) {
$my_arr[$k] = $v + 1;
}
echo "This completed in ", microtime(true) - $start, " seconds";
echo "<br>";
$start = microtime(true);
foreach ($my_arr as $k => &$v) {
$v = $v + 1;
}
echo "This completed in ", microtime(true) - $start, " seconds";
echo "<br>";
$start = microtime(true);
foreach ($my_arr as $k => $v) {}
echo "This completed in ", microtime(true) - $start, " seconds";
echo "<br>";
$start = microtime(true);
foreach ($my_arr as $k => &$v) {}
echo "This completed in ", microtime(true) - $start, " seconds";
?>

结果

This completed in 0.00058293342590332 seconds
This completed in 0.00063300132751465 seconds
This completed in 0.00023412704467773 seconds
This completed in 0.00026583671569824 seconds
© 2010-2022 XuLaLa 保留所有权利 本站由 WordPress 强力驱动
请求次数:69 次,加载用时:0.665 秒,内存占用:32.19 MB