Looking for more information on how to do PHP the right way? Check out PHP: The Right Way

Simon Holywell:
Memoization or function cache
May 18, 2015 @ 16:09:17

Simon Holywell's latest post shares an interesting feature of PHP's static function handling that lets you cache the results of a function call to improve performance.

A little known feature of PHP’s static keyword is that it allows for memoization or function caching. This is a process whereby a functions heavy lifting can be cached so that subsequent calls are faster. It is possible to store any value in a memoized way such as arrays or even objects. This is done without any external side effects - that is to say that the code calling the function will require no changes to support memoization.

He includes an example of this in action, showing the use of a "static" keyword on a variable over two function calls. He goes through and explains how it works and the flow of the simple function. He builds this up a bit and shows the same functionality in the handling (and parsing) of a JSON document. He then gets more into the "real world" usage of this kind of static handling, pointing out that it can be very useful for caching without the need for an external service (like memcache or redis). His final example shows the caching of a function call using the same method and dependent on the arguments provided.

tagged: function cache static example tutorial memoization

Link: https://www.simonholywell.com/post/2015/05/memoization-or-function-cache/


Trending Topics: