Home > Mobile >  When iterating over a 2D structure, is it faster to iterate over the total length or use nested loop
When iterating over a 2D structure, is it faster to iterate over the total length or use nested loop

Time:10-26

I can think of two different ways to iterate over a 2d range, either using nested loops to iterate over the rows and columns separately:

for (int i = 0; i < width * height; i  ) {
    int x = i % width;
    int y = i / width;
    //Do stuff
}

or using a single for loop to iterate over the area and computing the row and column:

for (int y = 0; y < height; y  ) {
    for (int x = 0; x < width; x  ) {
        //Do stuff
    }
}

In my application width and height can be very large, so I need to know which one will perform better for large numbers of iterations.

CodePudding user response:

width * height might overflow. Signed integer overflow is (still) undefined behavior. i % 0 is undefined behavior. i / 0 is undefined behavior too. You can protect the first version against such problems, though in the second version none of this issues is present.

Don't do premature optimization. This:

for (int y = 0; y < height; y  ) {
    for (int x = 0; x < width; x  ) {
        //Do stuff
    }
}

Is simpler and more readable than the flat loop, and on top of that it is correct (irrespective of the values of height and width).

If you do care about performance, you should first write correct and tested code and then measure and profile it.

  • Related