Cpp plus 1
Cpp plus 1

Reputation: 1010

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?

Upvotes: 1

Views: 65

Answers (3)

wildplasser
wildplasser

Reputation: 44250

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

   while(anIndex < aVaryingBoundary) {
       if(something) {
           //code
           if(anIndex < aVaryingBoundary) continue;
           else break;
        }
        //more code
    }
}

Upvotes: 0

melpomene
melpomene

Reputation: 85837

Isn't that just

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

?

Upvotes: 3

iBug
iBug

Reputation: 37297

In this way you need no gotos, and the compiler may be able to optimize it.

if(anIndex < aVaryingBoundary) {
    f += .001f;
    // Tag loop:
    while (true) {
        if(something) {
            //code
            if(anIndex < aVaryingBoundary) {
                continue;
            }
            else {
                break;
            }
        }
        //more code
        if(anIndex < aVaryingBoundary) {
            continue;
        }
        break;
    }
}
// Tag loop_end:

The main logical structure remains unchanged, but there's no more gotos.

Upvotes: 2

Related Questions