开发者

What's faster ? if() function() OR function(){ if() }? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance. Closed 11 years ago.

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


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜