In C, when compiled to a x86 machine, I would usually replace branches with logical expression, when speed is the most important aspect, even if the conditions are complex, for example, instead of
char isSomething() {
if (complexExpression01) {
if (complexExpression02) {
if(!complexExpression03) {
return 1;
}
}
}
return 0;
}
I will write:
char isSomething() {
return complexExpression01 &&
complexExpression02 &&
!complexExpression03 ;
}
Now clearly, this might be a harder to maintain, and less readable code, but it might actually be faster.
Is there any reason to act the same way when working with managed code, such as C#? Are "jumps" expensive in managed code as they are in unmanaged code (at least on x86)?
The two expressions will result in the same number of tests, as the logical and operator (
&&
) has short-circuit semantics in both C and C#. The premise of your question (that the second way of expressing the program results in less branching) is therefore incorrect.