Search code examples
c++performancecompiler-optimizationloop-invariant

in C++, is it more efficient to have "if" outside of a for loop or have the "if" in the for loop


I am writing a program in C++ and I am debating whether to put the "if"s inside the loop. I would imagine doing one check and then looping would be overall more efficient rather than the constant loop and check, but I am not quite sure. Or does any of this not matter because the compiler will optimize it anyway?

Is this more efficient?

for(int i = 0; i < SOME_BOUND; i++){
    if(SOME_CONDITION){
        //Some actions
    }
    else {
        //Some actions
    }

}

or is this more efficient?

if(SOME_CONDITION){
    for(int i = 0; i < SOME_BOUND; i++){
        //Some Actions
    }
}
else {
    for(int i = 0; i < SOME_BOUND; i++){
        //Some Actions
    }
}

Solution

  • One check is definitely better, however there are features both in hardware (branch prediction) and compiler (hoisting expressions and conditionals outside the loop) which make it hard to predict whether there will actually be a runtime difference between the two pieces of source code.

    Generally you should focus on correctness and maintainability, and only go duplicating loops for performance reasons if profiling shows that the optimizer is missing out on performance.