用于优化的静态变量
我想知道是否可以使用静态变量进行优化:
public function Bar() {
static $i = moderatelyExpensiveFunctionCall();
if ($i) {
return something();
} else {
return somethingElse();
}
}
我知道一旦 $i
被初始化,它就不会被连续调用 Bar 时的该行代码所改变()
。我假设这意味着moderatelyExpectiveFunctionCall()
不会在我每次调用时都被评估,但我想确定一下。
一旦 PHP 看到一个已初始化的静态变量,它是否会跳过该行代码?换句话说,如果我对 Bar()
进行大量调用,这会优化我的执行时间,还是在浪费时间?
I'm wondering if I can use a static variable for optimization:
public function Bar() {
static $i = moderatelyExpensiveFunctionCall();
if ($i) {
return something();
} else {
return somethingElse();
}
}
I know that once $i
is initialized, it won't be changed by by that line of code on successive calls to Bar()
. I assume this means that moderatelyExpensiveFunctionCall()
won't be evaluated every time I call, but I'd like to know for certain.
Once PHP sees a static variable that has been initialized, does it skip over that line of code? In other words, is this going to optimize my execution time if I make a lot of calls to Bar()
, or am I wasting my time?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我发现执行下面的代码更容易。这样缓存是全局完成的,而不是每个函数的实现。
I find it easier to do something like the code below. That way the caching is done globally instead of per implementation of the function.
static $i = blah()
无法编译,因为 php 不允许在静态初始值设定项中进行表达式和函数调用。你需要类似的东西static $i = blah()
won't compile, because php doesn't allow expressions and function calls in static initializers. You need something like这应该适用于您的(非常简单)情况:
对于全局缓存机制,您可以使用类似于 这个。
This should work in your (quite simple) case:
As for a global caching mechanism, you may use a method similar to this one.
这是一个相当简短的方法:
Here is quite shorter approach:
怎么样:
How about: