Search code examples
phpmysqloptimizationperformance-testing

Does PHP not optimize in this way? Is it top-down interpreted language?


I'm trying to figure out why my pages are taking so long to load. I have a page with like 30 calls to get_template_directory_uri() and the implementation of that function makes calls to the database, but the value returned by the function is the same for the entirety of my page generation. Therefore I should probably do something like

$tduri = get_template_directory_uri();

and use $tduri as needed, at least as a good practice, but is this totally necessary or would the value of get_template_directory_uri() have been cached anyways?


Solution

  • PHP does not cache return values of functions by itself. In your case the function is making a call to an external database, so how could PHP even know if the result was the same or different each time the function was called?

    Also consider that any call to an external system is highly likely to be slower than storing a variable within a PHP script.

    So yes, absolutely, cache the return value somewhere suitable and always test whether it makes a noticeable improvement, sometimes the results can be suprising. There are many good ways to profile PHP, microtime is very quick for ad-hoc testing without requiring additional set-up. Search for 'PHP profiling' to get the more powerful tools.