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

前端 未结 7 663
庸人自扰
庸人自扰 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-13 23:54

    While exploring this on an intel processor I found no differene in execution times, possibly due to multiple integer execution units.

    But when doing this on 16MHZ real-time microprocessor with neither branch prediction nor integer execution units there were notable differences.

    1 million iterations of the slower code took 1761 ms

    int slower(char *a, long i)
    {
      if (i < 0 || i >= 10)
        return 0;
    
      return a[i];
    }
    

    1 million iterations faster code took 1635 ms

    int faster(char *a, long i)
    {
      if ((unsigned int)i >= 10)
        return 0;
      return a[i];
    }
    

提交回复
热议问题