非平凡的 goto 使用(可能击败编译器)

Non-trivial goto use (might beat compiler)

我有一段代码是这样的:

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
}

我发现使此代码更高效(通过消除不必要的 f 增量)的唯一方法是使用 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:

尽管这是一个简单的优化,但我认为编译器不会轻易检测到这一点。编译器执行真的很重要吗?

这样就不需要goto,编译器或许可以优化。

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:

主要逻辑结构保持不变,但没有更多goto

不就是吗

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

?

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

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