避免重复/循环非开关

Cha*_*les 7 c optimization dry

我有一个紧密循环运行的热点代码:

for (i = 0; i < big; i++)
{
    if (condition1) {
        do1();
    } else if (condition2) {
        do2();
    } else {
        do3();
    }
    // Shared code goes here
    // More shared code goes here
}
Run Code Online (Sandbox Code Playgroud)

由于condition1并且condition2是不变的,我将循环解开

if (condition1) {
    for (i = 0; i < big; i++)
    {
        do1();
        // Shared code goes here
        // More shared code goes here
    }
} else if (condition 2) {
    for (i = 0; i < big; i++)
    {
        do2();
        // Shared code goes here
        // More shared code goes here
    }
} else {
    for (i = 0; i < big; i++)
    {
        do3();
        // Shared code goes here
        // More shared code goes here
    }
}
Run Code Online (Sandbox Code Playgroud)

这样运行得更好,但我想知道是否有一种聪明的方法来做到这一点而不重复自己?

Str*_*239 4

另一种可能稍微更有效的选择是使用宏来为您构建代码:

#define DO_N(name, ...) for(int i = 0; i < big; i++){name(__VA_ARGS__);/*shared code*/}

if (condition1) {
    DO_N(do1, .../*arguments here*/)
} else if (condition 2) {
    DO_N(do2, ...)
} else {
    DO_N(do3, ...)
}

#undef DO_N
Run Code Online (Sandbox Code Playgroud)

它很难看,但我认为它可以满足您的要求,并且可能允许内联函数指针不允许的地方。

此外,您可能会发现将共享代码放在单独的宏或函数中更具可读性。