1

Let's say that I have a 9-by-9 2-D array. Is there a difference between looping through with a single loop or multiple loops?

for (int i = 0; i < 81; i++)
  currentEdit[i / 9][i % 9] = 0;

VS.

for (int i = 0; i < 9; i++)
   for (int j = 0; j < 9; j++)
      currentEdit[i][j] = 0;
4
  • 1
    Well, the first uses divisions, the second doesn't. Assuming the compiler doesn't just make them the same on its own, the second would be better since it doesn't have divisions, and is easier to read. Commented Apr 9, 2020 at 23:28
  • The second set of loops will generate better assembly.. but I honestly don't see it making much of a difference unless this is extremely critical.. Commented Apr 9, 2020 at 23:49
  • 3
    You should not assume the memory layout, and the code should be transparent as to what it's actually doing. 2nd version. Commented Apr 9, 2020 at 23:51
  • Does it need to be a 2D array? Commented Apr 29, 2020 at 6:03

1 Answer 1

2

The right choice is multiple loops. Keep in mind that it will perform much less operations since it does not have to divide or calculate the module to access the array position.

This is the right choice:

for (int i = 0; i < 9; i++)
   for (int j = 0; j < 9; j++)
      currentEdit[i][j] = 0;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.