Optimization of Cyclic Operations in PHP
Even a light operation, repeated multiple times in a loop, can consume a lot of resources.
Let's look at an example. Suppose we are given an array:
<?php
$arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
?>
Let's find the average of the elements of this array. To do this, you need to find the sum of the elements and divide it by the quantity. Suppose some programmer has already solved this problem in the following way:
<?php
$sum = 0;
foreach ($arr as $elem) {
$sum += $elem / count($arr);
}
echo $sum;
?>
Let's consider the problems with this solution. Technically, the code works correctly and gives the correct answer. The fact is that it is mathematically correct to divide the entire sum by the quantity, as well as to divide each of the terms by the quantity.
However, another problem arises. The fact is that we will perform the division as many times as there are elements in our array. And it turns out that we are doing a large number of unnecessary operations, because the division could have been done at the end - once, by dividing the entire found sum.
Let's optimize our code:
<?php
$sum = 0;
foreach ($arr as $elem) {
$sum += $elem;
}
echo $sum / count($arr);
?>
Optimize the code below:
<?php
for ($i = 1; $i <= 31; $i++) {
if ($i === date('d')) {
echo "<b>$i</b><br>";
}
if ($i !== date('d')) {
echo "$i<br>";
}
}
?>