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

前端 未结 7 675
庸人自扰
庸人自扰 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:03

    Note that this trick won't work if your project is checked instead of unchecked. Best case it will be slower (because each cast will need to be checked against overflow) (or at least not-faster), worst case you will get an OverflowException if you try to pass -1 as the index (instead of your exception).

    If you want to write it "correctly" and in a more "will surely work" way, you should put a

    unchecked
    {
        // test
    }
    

    all around the test.

提交回复
热议问题