What's wrong with Loop speed?

c#, for-loop, loops, performance

Solution

why it runs faster since it's just a number

It is not just a number, it is a property. With a nontrivial implementation, unfortunately, there's an underlying unmanaged interop call involved that isn't very cheap. It blows up to an observable overhead due to the O(n^2) loop complexity.

You can simply solve it by caching the property value yourself:

int width = _img.Width;
int height = _img.Height;
for (int aRowIndex = 0; aRowIndex < width; aRowIndex += subsample)
{
    for (int aColumnIndex = 0; aColumnIndex < height; aColumnIndex += subsample)
    {
    }
}

Problem

I have this simple `for` loop with nothing inside. It takes almost 2 seconds to run, now, but if I replace the `_img.width` with 512 then it runs almost in 0.001 milliseconds. What's the problem? Should I assign a local variable instead of using `_img.width`? I'm wondering why it runs faster since it's just a number. ``` for (int aRowIndex = 0; aRowIndex < _img.width; aRowIndex += subsample)// For por cada fila de cada imagen { for (int aColumnIndex = 0; aColumnIndex < _img.height; aColumnIndex += subsample)//For por cada columna { } } ```

Original source