Search code examples
coptimizationgoto

Non-trivial goto use (might beat compiler)


I had a piece of code that was like this:

f += .001f; //Only needs to be executed when loop executes at least one iteration, but does no harm if incremented without entering the loop
while(anIndex < aVaryingBoundary) {
    if(something) {
        //code
        continue;
    }
    //more code
}

The only way I found to make this code more efficient (by eliminating unnecessary increments of f) was to use goto.

if(anIndex < aVaryingBoundary) {
    f += .001f;

loop:
    if(something) {
        //code
        if(anIndex < aVaryingBoundary) {
            goto loop;
        }
        else {
            goto loop_end;
        }
    }
    //more code
    if(anIndex < aVaryingBoundary) {
            goto loop;
    }
}
loop_end:

Even though this is a simple optimization, I don't think the compiler can easily detect this. Is it really non-trivial for the compiler to perform?


Solution

  • Isn't that just

    if (anIndex < aVaryingBoundary) {
        f += .001f;
        do {
            if(something) {
                //code
                continue;
            }
            //more code
        } while(anIndex < aVaryingBoundary);
    }
    

    ?