Do compilers produce better code for do-while loops versus other types of loops?

后端 未结 6 758
深忆病人
深忆病人 2020-12-08 01:48

There\'s a comment in the zlib compression library (which is used in the Chromium project among many others) which implies that a do-while loop in C generates "better&q

6条回答
  •  执笔经年
    2020-12-08 02:12

    A while loop is often compiled as a do-while loop with an initial branch to the condition, i.e.

        bra $1    ; unconditional branch to the condition
    $2:
        ; loop body
    $1:
        tst  ; the condition
        brt $2    ; branch if condition true
    

    whereas the compilation of a do-while loop is the same without the initial branch. You can see from that that while() is inherently less efficient by the cost of the initial branch, which is however only paid once. [Compare to the naive way of implementing while, which requires both a conditional branch and an unconditional branch per iteration.]

    Having said that, they aren't really comparable alternatives. It is painful to transform a while loop into a do-while loop and vice versa. They do different things. And in this case the several method calls would totally dominate whatever the compiler did with while as against do-while.

提交回复
热议问题