What is code hoisting?


Code hoisting is an optimization technique that moves code from inside a loop to outside of the loop, if the code is not dependent on being inside the loop (i.e., the code moved is loop-invariant).

If your compiler doesn’t have an optimizer, then the optimization can be performed manually in the source code. If the compiler has a decent optimizer and the appropriate optimization options are enabled, the compiler can hoist the code out of the loop for you, in the generated code.

As a very simple example, let’s say we have written this function in C:

void initWithSum(int list[], int count,
         int v1, int v2, int v3)
{
    for (int i = 0; i < count; i++)
    {
        list[i] = v1 + v2 + v3;
    }
}

Without any optimization, the expression v1 + v2 + v3 would be evaluated on every iteration of the loop. This is not very efficient. The loop is supposed to store the exact same value into every element of the array, and the expression that calculates the value doesn’t change based on where we are in the loop. So, that expression is loop-invariant.

With code hoisting enabled, the compiler can hoist the calculation of the sum completely out of the loop, in the generated code, which would be the equivalent of:

void initWithSum(int list[], int count, int v1, int v2, int v3)
{
    int temp = v1 + v2 + v3;

    for (int i = 0; i < count; i++)
    {
        list[i] = temp;
    }
}

The expression is evaluated only once, before the loop begins.

There are more complex situations, but this should give you the general idea of what code hoisting is.

Leave a Reply