Reputation: 3341
I wonder to know does function_exists() cache its queries internally?
Upvotes: 4
Views: 391
Reputation: 3341
No it doesn't, the following performance tests are confirming the fact:
function function_exists_cached($function_name)
{
static $cache = array();
if(isset($cache[$function_name]))
return $cache[$function_name];
return ($cache[$function_name] = \function_exists($function_name));
}
$funcs = \array_shift(\get_defined_functions());
$a = new \core\utiles\loadTime;
$times = $tot = 0;
$a->start();
/**
* None Cached: No cache used here
**/
for($index = 0; $index<count($funcs); $index++)
{
foreach($funcs as $func)
{
$times++;
if(\function_exists($func)) ;
}
}
$s = $a->stop();
$tot+=$s;
echo "<b>None Cached : </b><b><span style='color:green'>#$times</span></b> function check took : $s seconds<br />";
$b = new \core\utiles\loadTime;
$times = 0;
$b->start();
/**
* Fly Cached: An inline cache used here
**/
static $func_check = array();
for($index = 0; $index<count($funcs); $index++)
{
foreach($funcs as $func)
{
$times++;
if(!isset($func_check[$func]))
{
if(\function_exists($func)) ;
$func_check[$func] = 1;
}
else $func_check[$func];
}
}
$s = $b->stop();
$tot+=$s;
echo "<b>Fly Cached : </b><b><span style='color:green'>#$times</span></b> function check took : $s seconds<br />";
$c = new \core\utiles\loadTime;
$times = 0;
$c->start();
/**
* Function Cached: Has the same logic like Fly Cached section,
* But implemented in a function named function_exists_cached()
**/
for($index = 0; $index<count($funcs); $index++)
{
foreach($funcs as $func)
{
$times++;
if(\function_exists_cached($func)) ;
}
}
$s = $c->stop();
$tot+=$s;
echo "<b>Function Cached : </b><b><span style='color:green'>#$times</span></b> function check took : $s seconds<br />";
echo "Total time : $tot seconds";
None Cached : #2365444 function check took : 0.69758 seconds
Fly Cached : #2365444 function check took : 0.5307 seconds
Function Cached : #2365444 function check took : 1.02575 seconds
Total time : 2.25403 seconds
function_exists_cached($function_name)
has the same implementation of Fly Cached code lines, why does it take that much time??
Upvotes: 0
Reputation:
No, it does not. It just checks whether the function is defined in the function table. Simple enough.
However, the Zend Opcache extension may optimize out some calls to function_exists()
and certain other functions which can in some cases be evaluated at compile time. (It only optimizes out calls to function_exists()
where the function is defined internally by PHP, or by an extension.)
Upvotes: 5