Most, if not all modern processors utilize a technique called "branch prediction", with which it guesses what way to go in an if-then-else branch.
I have a question considering the scheme. Let's say we have this piece of code, in no specific language:
if(someCondition)
{
// some action
return someValue;
}
// some other action
return someOtherValue;
Logically speaking, that code is equivalent to this code:
if(someCondition)
{
// some action
return someValue;
}
else
{
// some other action
return someOtherValue;
}
The branch predictor would 'predict' the branch in the second example, but what about the first example? Will it guess? What will be loaded into the pipeline? Is there any speed to be gained with either of the examples disregarding the impact of actual code in the blocks?
My guess, it is dependent on the compiler: If statements are implemented (in assembly) using jumps which are only undertaken if the compare flag in the register is set. Now what exactly the assembly instructions will look like depends on the compiler. Unless there is a common way of handling it that every compiler does, which I doubt there is, then this is compiler dependent. In that case, what would happen on the latest Visual Studio C++ and GC++ compilers?
As hexafraction pointed out, the relation between the return values as well as how someCondition
is determined... the branch predictor might not kick in. Let us consider only true and false as return values. For the condition, let us assume both that it is a field which has been predetermined, either inside or outside the function, a local variable, and some arithmetic statement.
To be honest, I do not suspect there is much difference between the case that the condition is a local variable and the case that the field has been predetermined in the same function.
someCondition
is calculated and the relation between the two return values, it is theoretically possible that in some cases branch-less logic/bit twiddling/arithmetic may be possible. Additionally, architectures such as ARM have conditional execution, meaning that a lot of logic that would involve branching can be done branchlessly. Conditional instructions carry a condition as part of the opcode, and if the condition isn't met the inst. is turned into a nop. – Gaylegayleen