24
Nov '12
This is a rather simple idea yet one that I see people failing to implement again and again with serious impacts on processor load and processing time as a result.
If you have a function within an object that does any processor-intensive logic (complex SQL queries etc) and this function will be run more than once in a single execution thread of your application then caching the output of that function could make a big difference.
Very simply, all you need is to create an object variable to hold the cached output of the function and then within your function add a conditional like so:
if(!$this->cached_function_output) { //Do your logic $this->cached_function_output = $result_of_logic; } return $this->cached_function_output;
It’s just that simple! And you can ‘expire’ your cache any time you like by simply setting its value to null:
$this->cached_function_output = null;