题
我想知道如果我可以使用用于优化的一个静态变量:
public function Bar() {
static $i = moderatelyExpensiveFunctionCall();
if ($i) {
return something();
} else {
return somethingElse();
}
}
我知道,一旦$i
被初始化时,它不会被通过在连续调用Bar()
改变由该代码行。我的假设的,这意味着moderatelyExpensiveFunctionCall()
不会每次我打电话的时间进行评估,但是我想知道肯定。
在PHP看到已初始化一个静态变量,它跳过该代码行?换句话说,这是怎么回事,如果我做了很多电话给Bar()
优化我的执行时间,还是我浪费我的时间?
解决方案
我觉得更容易做一些像下面的代码。这种方式,缓存全局代替每执行功能的完成。
function moderatelyExpensiveFunctionCall()
{
static $output = NULL;
if( is_null( $output ) ) {
//set $output
}
return $output;
}
其他提示
static $i = blah()
不会编译,因为PHP不允许表达式和在静态初始化函数调用。你需要像
function foo() {
static $cache = null;
if(is_null($cache)) $cache = expensive_func();
do something with $cache
}
这应该在你的(很简单)情况下工作:
function your_function() {
static $output;
if (!isset($output)) {
$output = 'A very expensive operation';
}
return $output;
}
作为一个全局高速缓存机制,可以使用类似的这一项。
下面是相当短的方法:
function stuff()
{
static $smthg = []; // or null, or false, or something else
if ($smthg) {
return $smthg;
}
// filling $smthg goes here
// with a lot of
// code strings
return $smthg;
}
如何:
if (!isset($i))
{
static $i = moderatelyExpensiveFunctionCall();
}
不隶属于 StackOverflow