我要评分
获取效率
正确性
完整性
易理解

Loop-Invariant Code Motion

Principles

Loop-invariant code motion recognizes computations within a loop that produce the same result each time the loop is executed and moves them outside the loop body. This can effectively reduce the number of computations in the loop and speed up the code running. The compiler can optimize some code without changing the code. If an expression has a pointer or reference, the compiler does not automatically optimize the expression.

Modification Method

Before:
void fun(int arrayA [], int *p) {
    for (int i = 0; i < ARRAYLEN; ++i) {
        arrayA [i] = *p + *p + i;
    }
}

After:

void fun(int arrayA [], int *p) {
    int tmp = *p + *p;
    for (int i = 0; i < ARRAYLEN; ++i) {
        arrayA [i] = tmp + i;
    }
}