Is it more efficient to perform a range check by casting to uint instead of checking for negative values?

前端 未结 7 662
庸人自扰
庸人自扰 2020-12-13 23:31

I stumbled upon this piece of code in .NET\'s List source code:

// Following trick can reduce the range check by one
if ((uint) index >= (uint)_size) {
           


        
相关标签:
7条回答
  • 2020-12-14 00:13

    From MS Partition I, section 12.1 (Supported data types):

    The signed integer types (int8, int16, int32, int64, and native int) and their corresponding unsigned integer types (unsigned int8, unsigned int16, unsigned int32, unsigned int64, and native unsigned int) differ only in how the bits of the integer are interpreted. For those operations in which an unsigned integer is treated differently from a signed integer (e.g., in comparisons or arithmetic with overflow) there are separate instructions for treating an integer as unsigned (e.g., cgt.un and add.ovf.un).

    That is, the conversion from an int to a uint is merely a matter of book-keeping - from now on, the value on the stack/in a register is now known to be an unsigned int rather than an int.

    So the two conversions should be "free" once the code is JITted, and then the unsigned comparison operation can be performed.

    0 讨论(0)
提交回复
热议问题