PHP 中 FOR 与 FOREACH 的性能对比

phpserver side programmingprogramming更新于 2025/8/5 7:22:17

与 'for' 循环相比,'foreach' 速度较慢。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

相关文章