Search code examples
c++loopsconvention

Loop checking convention


If I was going through a loop, say iterating a vector, and I don't want to do an action on some item in the vector, I can do it in two ways:

This is the one I prefer to use:

vector<int> vec;
void loopFunction(int toIgnore) {
    for (size_t index = 0; index < vec.size(); index++) {
        if (vec[index] == toIgnore) continue;
        // do stuff
    }
}

This is the one I see most people use:

vector<int> vec;
void loopFunction(int toIgnore) {
    for (size_t index = 0; index < vec.size(); index++) {
        if (vec[index] != toIgnore) {
            // do stuff
        }
    }
}

I know in the final results there is absolutely no difference. However, is there any difference under the hood since the second way opens a new scope to execute? Is any of these two preferred over the other?

Thanks


Solution

  • As stated in my comment, on a personal level, I prefer the first implementation using continue in order to prevent unnecessary code nesting and scope creation.

    The only performance overhead from each, in addition to the normal code that will be implemented, is the evaluation of the expression in the if-statement. Since they both contain an expression to be evaluated, they're the same performance wise.

    If you think about how this is compiled, for C/C++, its straight into assembly code. On that level no matter how you nest the code, it compiles into simple jmp and cmp commands. Therefore, regardless of the implementation, on compile, you'll have the ~same assembly code.

    Either way you look at it, this is a micro-micro-micro optimization, if at all! Do what you prefer for code formatting and styling.