w3resource

PHP Exercises: Memoize a given function results in memory

PHP: Exercise-99 with Solution

Write a PHP program to memoize a given function results in memory.

Note: In computing, memoization or memoisation is an optimization technique used primarily to speed up computer programs by storing the results of expensive function calls and returning the cached result when the same inputs occur again.

Sample Solution:

PHP Code:

<?php
// Licence: https://bit.ly/2CFA5XY

// Function definition for 'memoize' that takes a function as a parameter
function memoize($func)
{
    // Use an anonymous function to create a closure that captures and persists a static cache variable
    return function () use ($func) {
        // Static cache variable to store memoized results
        static $cache = [];

        // Get the arguments passed to the memoized function
        $args = func_get_args();

        // Serialize the arguments to create a cache key
        $key = serialize($args);

        // Flag to indicate whether the result is retrieved from the cache or calculated
        $cached = true;

        // Check if the result for the current arguments is already in the cache
        if (!isset($cache[$key])) {
            // If not in the cache, calculate the result using the original function and store it in the cache
            $cache[$key] = $func(...$args);
            $cached = false;
        }

        // Return an associative array containing the result and a boolean indicating whether it was cached
        return ['result' => $cache[$key], 'cached' => $cached];
    };
}

// Create a memoized version of the 'add 10' function using 'memoize'
$memoizedAdd = memoize(
    function ($num) {
        return $num + 10;
    }
);

// Call the memoized function with an argument and display the result and cache status using 'var_dump'
var_dump($memoizedAdd(5));

// Call the memoized function with another argument and display the result and cache status using 'var_dump'
var_dump($memoizedAdd(6));

// Call the memoized function with the same argument as before and display the result and cache status using 'var_dump'
var_dump($memoizedAdd(5));
?>

Sample Output:

array(2) {
  ["result"]=>
  int(15)
  ["cached"]=>
  bool(false)
}
array(2) {
  ["result"]=>
  int(16)
  ["cached"]=>
  bool(false)
}
array(2) {
  ["result"]=>
  int(15)
  ["cached"]=>
  bool(true)
}

Flowchart:

Flowchart: Memoize a given function results in memory.

PHP Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous:Write a PHP program to create a new function that composes multiple functions into a single callable.
Next: Write a PHP program to curry a function to take arguments in multiple calls.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.