PHP中FOR与FOREACH的性能
与“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
热门推荐
10 儿子立冬祝福语简短独特
11 对当兵的祝福语简短
12 侄儿高考试祝福语简短
13 伴郎红包祝福语朋友简短
14 媳妇生日简短祝福语朋友
15 公司年会祝福语简短最好
16 元旦感恩祝福语简短大全
17 红包祝福语简短10字
18 周六早晨祝福语简短