功能中的過早返回效率 - Efficiency of premature return in a function

問題:

This is a situation I encounter frequently as an inexperienced programmer and am wondering about particularly for an ambitious, speed-intensive project of mine I'm trying to optimize. 這是我作爲一個經驗不足的程序員經常遇到的情況,我特別想知道我正在努力優化的一個雄心勃勃,速度密集的項目。 For the major C-like languages (C, objC, C++, Java, C#, etc) and their usual compilers, will these two functions run just as efficiently? 對於主要的類C語言(C,objC,C ++,Java,C#等)及其常用的編譯器,這兩個函數是否同樣有效運行? Is there any difference in the compiled code? 編譯代碼有什麼區別嗎?

void foo1(bool flag)
{
    if (flag)
    {
        //Do stuff
        return;
    }

    //Do different stuff
}

void foo2(bool flag)
{
    if (flag)
    {
        //Do stuff
    }
    else
    {
        //Do different stuff
    }
}

Basically, is there ever a direct efficiency bonus/penalty when break ing or return ing early? 基本上,是有過當的直接效益獎金/罰款break荷蘭國際集團或return早期荷蘭國際集團? How is the stackframe involved? 堆棧框架是如何涉及的? Are there optimized special cases? 是否有優化的特殊情況? Are there any factors (like inlining or the size of "Do stuff") that could affect this significantly? 是否有任何因素(如內聯或“Do stuff”的大小)可能會對此產生重大影響?

I'm always a proponent of improved legibility over minor optimizations (I see foo1 a lot with parameter validation), but this comes up so frequently that I'd like to set aside all worry once and for all. 我總是支持改進可讀性而非次要優化(我通過參數驗證看到foo1很多),但這種情況頻頻出現,我想一勞永逸地拋開所有的擔憂。

And I'm aware of the pitfalls of premature optimization... ugh, those are some painful memories. 而且我意識到過早優化的陷阱......呃,這些都是一些痛苦的回憶。

EDIT: I accepted an answer, but EJP's answer explains pretty succinctly why the use of a return is practically negligible (in assembly, the return creates a 'branch' to the end of the function, which is extremely fast. The branch alters the PC register and may also affect the cache and pipeline, which is pretty minuscule.) For this case in particular, it literally makes no difference because both the if/else and the return create the same branch to the end of the function. 編輯:我接受了答案,但EJP的答案非常簡潔地解釋了爲什麼return的使用幾乎可以忽略不計(在彙編中, return創建了一個“分支”到函數的末尾,這非常快。分支改變了PC註冊並且也可能影響緩存和管道,這是非常小的。)特別是對於這種情況,它實際上沒有區別,因爲if/elsereturn創建了相同的分支到函數的末尾。


解決方案:

參考: https://stackoom.com/en/question/X5Af
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章