문제

I'm reading about how to force an operation to throw an overflow exception, and on the "try it yourself" section, I had it in a different place than the book. I'm curious if there's a performance issue associated with one spot or the other, as I'm not certain the underlying mechanics of the checked keyword.

The example in the book was doing a factorial, which will quickly throw an overflow, even with an unsigned long. This is the code that I came up with:

static long Factorial (long number) {
    long result = 1;

    for (int i = 2; i <= number; i++) {
        checked {
            result *= i;
        }
    }

    return result;
}

However, looking at the answer page in the back of the book, they had the checked wrapped around the entire body of the function, including the return and long result = 1;. Obviously you'll never need one in those places, so if anything, I would just wrap the for loop in the check.

Is the presence of it inside the loop causing some underlying CLR code to be generated repeatedly? (Like why you declare a variable before entering a for loop.) Or is there no overhead having it inside the loop?

도움이 되었습니까?

해결책

There is going to be little difference in terms of the compiled results.

The main difference is that any arithmetic operation within the checked block will use a different IL instruction. There aren't more instructions, just different ones. Instead of mul, you get mul.ovf - instead of add, you get add.ovf, etc.

Your version actually has slightly different behavior, however. Since you're putting the checked block in the tigher scope, the variable increment (i++) will still be unchecked. The original would have been checked all the way through, which means that the i++ could throw, not just the multiplication operation. This does mean your version is faster, but only because you're avoiding the overflow checks and changing the resulting behavior, not because of the scope change.

Is the presence of it inside the loop causing some underlying CLR code to be generated repeatedly?

No, it just means those IL instructions inside of that scope will get the different IL operation codes with overflow checks instead of the standard ones.

Or is there no overhead having it inside the loop?

There is no overhead (other than the extra overhead of the checks in the instructions itself).

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top