'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 seconds0.0002658367156982에 완료되었습니다.