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

后端 未结 6 757
深忆病人
深忆病人 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:15

    The remark is not about the choice of the control statement (do vs. while), it is about the loop unrolling !!!

    As you can see, this is a string comparison function (string elements probably being 2 bytes long), which could have been written with a single comparison rather than four in a shortcut-and expression.

    This latter implementation is for sure faster, as it does a single check of the end-of-string condition after every four element comparisons, whereas standard coding would involve one check per comparison. Said differently, 5 tests per 4 element vs. 8 tests per 4 element.

    Anyway, it will work only if the string length is a multiple of four or has a sentinel element (so that the two strings are guaranteed to differ past the strend border). Pretty risky !

提交回复
热议问题