简体   繁体   中英

Visual Studio performance optimization in branching

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? ie like never checks if x is larger than 5 and always run function B

It depends on whether or not the compiler "knows" that x will always be less than 5 .

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:

int x = 1;

if (x > 5)
    printf("Hello\n");
else
    printf("World\n");

The disassembly is:

    sub rsp, 40                 ; 00000028H
    lea rcx, OFFSET FLAT:??_C@_06DKJADKFF@World?6?$AA@
    call    QWORD PTR __imp_printf

x = 1 is provably less than 5 . 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.

int x;
cin >> x;

if (x > 5)
    printf("Hello\n");
else
    printf("World\n");

The disassembly is:

    cmp DWORD PTR x$[rsp], 5
    lea rcx, OFFSET FLAT:??_C@_06NJBIDDBG@Hello?6?$AA@
    jg  SHORT $LN5@main
    lea rcx, OFFSET FLAT:??_C@_06DKJADKFF@World?6?$AA@
$LN5@main:
    call    QWORD PTR __imp_printf

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:

const char *str = "Hello\n";

if (!(x > 5))
    str = "World\n";

printf(str);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM