Consider the following
while(true)
{
if(x>5)
// Run function A
else
// Run function B
}
if x is always less than 5, does visual studio compiler do any optimization? i.e. like never checks if x is larger than 5 and always run function B
It depends on whether or not the compiler “knows” that
xwill always be less than5.Yes, nearly all modern compilers are capable of removing the branch. But the compiler needs to be able to prove that the branch will always go one direction.
Here’s an example that can be optimized:
The disassembly is:
x = 1is provably less than5. So the compiler is able to remove the branch.But in this example, even if you always input less than 5, the compiler doesn’t know that. It must assume any input.
The disassembly is:
The branch stays. But note that it actually hoisted the function call out of the branch. So it really optimized the code down to something like this: