Reusing code within a loop without using functions

111 Views Asked by At

I have the following code which scans a 2D array row by row

for (int i = 0; i < rows; ++i)
{
    for (int j = 0; j < cols; ++j)
    {
        // Code here that scans a 2D array using i & j as the indices
    }
}

This is followed by another set of loops which scan the same array column by column

for (int j = 0; j < cols; ++j)
{
    for (int i = 0; i < rows; ++i)
    {
        // Code that is a near duplicate of the code in the previous set of loops
    }
}

The code inside the above 2 sets of loops are nearly identical. Is there any way I can remove the duplication? I would prefer not to move the code into a separate function as this code is going to be run quite often on a pretty huge array, and AFAIK there isn't a way to force inlining in C#.

1

There are 1 best solutions below

4
On

You may be interested in the AggressiveInlining option on methods

[MethodImpl(MethodImplOptions.AggressiveInlining)]
void Method2()
{
    // ... Aggressive inlining.
}

Source: https://www.dotnetperls.com/aggressiveinlining