Optimization of Repeating Heavy Operations in PHP
In the previous lesson, repeated function calls actually take very little time and our optimization will not save very much. However, things will be much worse if we make several calls to a "heavy" function that takes a long time to execute.
Let, for example, we have a function that finds the divisors of a number:
<?php
function getDivisors($num) {
$result = [];
for ($i = 1; $i <= $num; $i++) {
if ($num % $i == 0) {
$result[] = $i;
}
}
return $result;
}
?>
Obviously, this function is quite "heavy". Therefore, it would be a bad idea to write code like this:
<?php
$num = 123456;
if (array_sum(getDivisors($num)) >= 10 and array_sum(getDivisors($num)) <= 100) {
} else {
}
?>
It is better, of course, to perform the "heavy" operation once and write the result to a variable, and then use this variable in the necessary places:
<?php
$num = 123456;
$sum = array_sum(getDivisors($num));
if ($sum >= 10 and $sum <= 100) {
} else {
}
?>
Optimize the code below:
<?php
$num = 1233456789;
if (getSumSquare($num) >= 10 and getSumSquare($num) <= 100) {
echo 'correct';
} else {
echo 'incorrect';
}
function getSumSquare($num) {
$digits = explode('', $num);
$sum = 0;
foreach ($digits as $digit) {
$sum += $digit * $digit;
}
return $digit;
}
?>