
This recommendation is part of the open catalog of best practice rules for performance that is automatically detected and reported by Codee.
Issue
Outlining a loop to a dedicated function might significantly increase compiler and tooling code coverage.
Relevance
A huge part of the parallelization efforts are focused on parallelizing loops. Some static analysis tools and optimizing compilers are able to suggest parallelization hints. Functions usually contain loops that might be optimized or parallelized but static analyzers and compilers fail to detect them due to the existence of unsupported statements in a part of the function outside the loop itself. In those situations isolating the loop in a separate function may enable its detection as opportunities for optimization or parallelization.
Actions
Move the loop to a dedicated function and replace its original location by a call to that new function.
Code example
The following code might be obscure for static code analysis tools due to the dynamic allocation of a pointer-based struct data type in the C programming language:
#include <stdlib.h>
typedef struct
{
double *A;
double *B;
} data;
void foo()
{
data S;
S.A = (double *)malloc(sizeof(double) * 1000);
S.B = (double *)malloc(sizeof(double) * 1000);
for (size_t i = 0; i < 1000; i++)
{
S.A[i] = 0;
}
free(S.B);
free(S.A);
}
By outlining the loop to a dedicated function (see bar() in the code below) the loop can be easily analyzed in isolation because the resulting code is free of uses of the pointer-based struct data type. The resulting code is as follows:
#include <stdlib.h>
typedef struct
{
double *A;
double *B;
} data;
void bar(double *A)
{
for (size_t i = 0; i < 1000; i++)
{
A[i] = 0;
}
}
void foo()
{
data S;
S.A = (double *)malloc(sizeof(double) * 1000);
S.B = (double *)malloc(sizeof(double) * 1000);
bar(S.A);
free(S.B);
free(S.A);
}
Related resources

Building performance into the code from day one with Codee