Optimization of Unnecessary Arrays in PHP
Suppose a programmer is faced with the task
of finding the sum of integers from 1 to 100000000.
Our programmer wrote an elegant solution to this problem, like this:
<?php
echo array_sum(range(1, 100000000));
?>
A beautiful solution, isn't it? Just one line and all that. But it doesn't work! Try running this code and it will throw an error on the screen about requesting too much RAM.
Hmm, 100000000 doesn't seem like that much?
Or is it? Let's calculate. The range function
creates an array with 100000000 numbers.
Let's assume PHP allocates 2 bytes per number
- then storing our array would require
200000000 bytes, which is about
200 megabytes of RAM.
But in reality, much more RAM will be needed
because PHP has very high overhead costs for storing arrays.
For example, my error message says
that I'm trying to allocate 4294967304
bytes - something like 4 gigabytes!
Now it's clear why the error occurs - we have far exceeded the allowed memory limit.
It's not that hard to rewrite our script into another one, that barely consumes any RAM:
<?php
$sum = 0;
for ($i = 1; $i <= 100000000; $i++) {
$sum += $i;
}
echo $sum;
?>
Even better, let's use a mathematical solution:
<?php
$n = 1000000;
$sum = $n * ($n + 1) / 2;
echo $sum;
?>
A programmer was faced with the task of finding the factorial of a given number. He solved it in the following way:
<?php
$n = 100;
echo array_product(range(1, $n));
?>
Explain what is wrong with this code. Rework the code to be more optimal.
A programmer was faced with the task of finding
the number of digits needed to
write all integers from 1 to 1000000.
He solved it in the following way:
<?php
echo strlen(implode('', range(1, 1000000)));
?>
Explain what is wrong with this code. Rework the code to be more optimal.
A programmer was faced with the task of finding
the number of numbers divisible without a remainder by
7, located within a given
interval. He solved it in the following way:
<?php
$arr = [];
for ($i = 0; $i <= 1000; $i++) {
if ($i % 7 == 0) {
$arr[] = $i;
}
}
echo count($arr);
?>
Explain what is wrong with this code. Rework the code to be more optimal.
A programmer was faced with the task of finding the sum of divisors of a number. He solved it in the following way:
<?php
$num = 320;
$divs = [];
for ($i = 0; $i <= $num; $i++) {
if ($num % $i == 0) {
$divs[] = $i;
}
}
echo array_sum($divs);
?>
Explain what is wrong with this code. Rework the code to be more optimal.