function_exists()是否缓存其查询?

时间:2014-02-07 05:20:09

标签: php caching

我想知道function_exists()在内部缓存查询吗?

2 个答案:

答案 0 :(得分:5)

No, it does not.它只是检查函数是否在函数表中定义。很简单。

但是,the Zend Opcache extension may optimize out some calls to function_exists()和某些其他函数在某些情况下可以在编译时进行评估。 (它只优化对function_exists()的调用,其中函数由PHP或扩展内部定义。)

答案 1 :(得分:0)

不,它不,以下性能测试证实了这一事实:

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";

输出:

无缓存: #b65444 功能检查:0.69758秒
Fly Cached: #2365444 功能检查:0.5307秒
功能缓存: #2365444 功能检查:1.02575秒
总时间:2.25403秒

<小时/> 我想知道,考虑到function_exists_cached($function_name)具有相同的 Fly Cached 代码行的实现,为什么需要花费那么多时间?