Could type punning signed to unsigned integers make bounds checking faster by eliminating the need for >= comparison?

后端 未结 2 694
半阙折子戏
半阙折子戏 2021-02-08 00:46

Say I had a really performance-critical loop in my program where I need to check if a point was inside a rectangle, but I know at compile time that the lower bounds are always g

2条回答
  •  清酒与你
    2021-02-08 01:29

    Yes, it's a perfectly valid optimization when you're testing a signed integer and the lower bound is zero. In fact it's such a common optimization that your compiler will almost certainly do it automatically; obfuscating your code by doing it yourself is very likely to be a pointless premature optimization.

    I just tested this on GCC 4.9, and confirmed by inspecting the generated assembly code that it performs this optimization automatically at -O1 and above. I would expect all modern compilers to do the same.

提交回复
热议问题