什么更快? if() 函数() 或函数(){ if() }?
想象一下,您有一个函数在一种条件下执行某些操作,例如。如果数组不为空。
如果 $array
为空,它会更快吗:
function dostuff($array){
// stuff
}
if(!empty($array)) dostuff($array);
或者:
function dostuff($array){
if(!empty($array)){
// stuff
}
}
dostuff($array);
我知道,“你在这里谈论的是毫秒”,但我只是好奇,我会“编写这样的代码”无论如何,对我来说最有意义”;)
Imagine you have one function that does stuff under one condition, eg. if an array is not empty.
Would it be faster, in the case $array
is empty :
function dostuff($array){
// stuff
}
if(!empty($array)) dostuff($array);
Or :
function dostuff($array){
if(!empty($array)){
// stuff
}
}
dostuff($array);
I know, "you're talking about milliseconds here", but i'm just curious, and i will "write the code that makes the most sense to me" anyway ;)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
第一个更快,因为调用函数时会产生开销(或者更确切地说,您更早地进行检查),但实际上,永远不要考虑这一点,除非您在循环中执行 10.000 次...但是您应该内联它相反,如果函数非常简单,实际上会显着提高性能。
The first is faster as there is overhead when calling a function (or rather, you put the check earlier), but really, never ever think about this unless you are doing it 10.000 times in a loop... but then you should inline it instead if the function is so simple that it would actually noticeably improve performance.
我不知道 PHP 是否有运行时堆栈,但如果有的话,每当调用函数时,该例程中存储的所有变量都会被扔到该堆栈上,然后在函数终止后检索。如果您只需在 if 语句计算结果为 true 时执行该调用,那么就可以节省一点点时间。
也就是说,时间这么短,很可能没有理由担心。将 if 语句放在更有意义的地方。
I don't know how if PHP has a runtime stack, but if it does, whenever a function is called, all of the variables stored during that routine are thrown onto that stack and then retrieved once the function has terminated. If you only have to do that call when the if statement evaluates to true, then that is a teeny bit of time saved.
That said, it is such a small amount of time there is most likely no reason to worry about it. Put the if statement wherever it makes more sense to be.
如果您使用 分析器来实际检查,您会发现单个调用几乎无法测量,但是避免可能冗余的函数调用会更快一些。
我想建议您在这里关注可读性。如果您可以选择避免检查(该功能是自主的),那么就去做吧。
If you were to use a profiler to actually check you would find that it's hardly measurable for a single call, but avoiding the possibly redundant function call is a bit speedier.
I'd like to advise that you look onto readability here instead. If you have the option of avoiding a check (the function is autonomous), then go for that.