Ad space (banner)
๐Ÿ˜PHP Lessons
Lesson 38 / 68

Speeding Up Calculations with Memoization (Caching)

In this lesson you will learn the memoization technique so you can speed up expensive calculations efficiently. This is for anyone searching for "what is PHP memoization".

Memoization stores a result once it has been computed and returns it straight from storage the next time the same input arrives. Picture being asked the same question repeatedly and simply repeating the answer you remembered.

The sample code uses the $cache array as that storage and reaches it from inside slowSquare with global $cache;. isset($cache[$n]) checks whether the answer is already known and returns it immediately if so.

A common stumbling block for beginners is needing the global keyword to reach an outer variable from inside a function. PHP functions do not automatically see variables from the enclosing scope, so you have to declare it explicitly.

The heavier the computation, the bigger the payoff, which makes this a familiar idea in real performance work. Recursive calculations and cached API responses in particular show a speed-up you can feel.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run PHP directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)