Memoization in PHP
Honeybadger Staff
Posted on March 1, 2024
This article was originally written by Michael Barasa on the Honeybadger Developer Blog.
Memoization is an important optimization technique in software development. It involves boosting the performance of an application or software by caching the results. This ensures that the next time a function runs, it utilizes the cached information rather than running a fresh computation.
When implemented accurately, memoization reduces the number of resources that an application consumes. Consequently, the software runs more efficiently and delivers a better user experience.
Memoization is particularly important in PHP due to the single-threaded application architecture that's in place. The single-thread layout means that only specific code can run at one time. Developers have to utilize third-party libraries, such as Amp and Coroutines, to run concurrent requests, which may be tedious to implement, particularly for beginners. Memoization is an excellent way to speed up applications without implementing concurrency.
When should you use memoization?
You can use memoization in the following situations:
- Time-consuming functions. Implementing memoization can be helpful if your application uses functions that take a long time to execute and return results. Rather than running an entire function every time it's called, the application can retrieve information from the cached output. However, note that memoization is only appropriate for those functions that always return the same static value.
- Resource-intensive computations. You could also use memoization if your application consumes a large number of resources to perform repetitive tasks (such as calculations).
Example of memoization
In this section, we use a simple example to understand why we need memoization.
Okay, let's dive in!
Let's say we have a Fibonacci series where the value of the next number is the sum of the two previous numbers, as demonstrated below.
1,1,2,3,5,8,13,21,34 ...
In the above Fibonacci sequence, we obtained the last number (34) by summing up the two preceding numbers (13 and 21).
Then, we can use the following formula to determine the next number in the series.
fib(n)=fib(n-1)+fib(n-2)
We can also calculate the next value using the following recursive function.
function fibonacci($num){
// We first generate the first two numbers in the series
if ($num == 0){
return 0;
}else if ($num == 1){
return 1;
// We perform a recursive call to calculate the next number
else
return (fibonacci($num-1) + fibonacci($num-2));
}
// Driver Code
$fib_num = 5;
for ($counter = 0; $counter < $fib_num; $counter++){
echo fibonacci($counter),' ';
}
The above code generates a Fibonacci sequence that has five numbers. When you run this code, the output will appear in the following manner:
0 1 1 2 3
The above results are returned within milliseconds. When that happens, you may believe that you have written some highly efficient code! However, in reality, this is not true. Let's see why.
Change the value of fib_num
to 1000000000000
and then run the code.
You will see that the program will freeze or take longer to perform the computation.
Moreover, among the results that the program finally returns, you will see a fatal error during execution—that is, the program surpasses the maximum execution time of 120 seconds, as demonstrated below.
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946 17711 28657 46368 75025 121393 196418 317811 514229 832040 1346269 2178309 3524578 5702887 9227465 14930352 24157817 39088169 63245986 102334155 165580141
Fatal error: Maximum execution time of 120 seconds exceeded in C:\xampp\htdocs\pdfexample\index.php on line 46
Memoization can help address the delays encountered by the above program during execution. Rather than repeatedly performing the same computation, the program will simply retrieve cached outputs.
How to implement memoization in PHP
It is evident from the above example that running a Fibonacci sequence for large values is inefficient. The server takes a substantial amount of time to compute and return the results. The program also forces the system to allocate more resources to the execution of the program. This means that the speed of other programs may be negatively affected.
However, we can avoid unnecessary or extra computation by saving specific results in an array. Then, the program will retrieve values from the array and use them to determine the Fibonacci sequence.
Let's see how this is done.
The first thing is to define an array and add two initial values (0,1), as shown below.
$previousValues=array(0,1);
We can now proceed to create a new Fibonacci function, as shown below.
function fibonacci($n){
}
The above function requires an integer as a parameter. Thus, we check whether or not the value exists in the $previousValues
array using the following if
statement:
if(array_key_exists($n, $previousValues) ){
return $previousValues[$n]; //If the key is present, we return the saved values from the array.
}
If the key or value is not present in the array, we check if $n
is greater than 1
and then update the values in the $previousValues
array.
else {
if($n > 1) {
$result = fibonacci($n-1) + fibonacci($n-2);
$previousValues[$n] = $result;
return $result;
}
return $n;
}
Here's the entire code for the fibonacci
function with memoization implemented:
$previousValues=array(0,1);
function fibonacci($n) {
global $previousValues;
if(array_key_exists($n, $previousValues) ){
return $previousValues[$n];
}
else {
if($n > 1) {
$result = fibonacci($n-1) + fibonacci($n-2);
$previousValues[$n] = $result;
return $result;
}
return $n;
}
}
$number = 10;
echo fibonacci($number);
When you run the above fibonacci
function, it will return the output much faster compared to the previous method that did not use memoization.
Pitfalls to watch out for
Memoization is a cool technique for improving the execution speed of your program. However, it also has its disadvantages. For example, memoization may cause your program to take up extra storage space, particularly if you provide a greater amount of input. Furthermore, memoization may also have a slower initial execution time and may require developers to add extra code to their applications to achieve the execution.
Conclusion
In this article, we discussed how to implement memoization in PHP. When applied accurately, memoization can bring noticeable speed and performance changes to your application. However, you should be careful with its implementation, as it may cause your app to consume more storage.
Posted on March 1, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.