Memoization in PHP

Dive into the world of caching and optimization techniques with PHP's memoization. Learn how this powerful tool can revolutionize your code, reduce redundant computations, and supercharge your application's performance.

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.

What to do next:
  1. Try Honeybadger for FREE
    Honeybadger helps you find and fix errors before your users can even report them. Get set up in minutes and check monitoring off your to-do list.
    Start free trial
    Easy 5-minute setup — No credit card required
  2. Get the Honeybadger newsletter
    Each month we share news, best practices, and stories from the DevOps & monitoring community—exclusively for developers like you.
    author photo

    Michael Barasa

    Michael Barasa is a software developer. He loves technical writing, contributing to open source projects, and creating learning material for aspiring software engineers.

    More articles by Michael Barasa
    Stop wasting time manually checking logs for errors!

    Try the only application health monitoring tool that allows you to track application errors, uptime, and cron jobs in one simple platform.

    • Know when critical errors occur, and which customers are affected.
    • Respond instantly when your systems go down.
    • Improve the health of your systems over time.
    • Fix problems before your customers can report them!

    As developers ourselves, we hated wasting time tracking down errors—so we built the system we always wanted.

    Honeybadger tracks everything you need and nothing you don't, creating one simple solution to keep your application running and error free so you can do what you do best—release new code. Try it free and see for yourself.

    Start free trial
    Simple 5-minute setup — No credit card required

    Learn more

    "We've looked at a lot of error management systems. Honeybadger is head and shoulders above the rest and somehow gets better with every new release."
    — Michael Smith, Cofounder & CTO of YvesBlue

    Honeybadger is trusted by top companies like:

    “Everyone is in love with Honeybadger ... the UI is spot on.” 
    Molly Struve, Sr. Site Reliability Engineer, Netflix
    Start free trial