0

If we had two arrays,

bool trueFalse[10][10];
bool falseTrue[100];

and we looped through them like this:

for(int i = 0; i < 10; i++)
{
    for(int k = 0; k < 10; k++)
    {
        trueFalse[i][k] = !trueFalse[i][k];
    }
}

for(int i = 0; i < 100; i++)
{
    falseTrue[i] = !falseTrue[i];
}

Which would be faster? Or would it be the same?

Update:

This is specifically for non-dynamic data. The sizes of the arrays will be set once, but after that they wont be changed again.

Daniel
  • 589
  • 4
  • 19
  • 1
    of course looping 1D is faster cause its O(n) while looping 2D has O(n2) complexity – Ali Kazmi Oct 03 '14 at 04:38
  • @AliKazmi, his 2D has the same total size than his 1D so overall is it very similar. – Alexis Wilke Oct 03 '14 at 04:38
  • @AliKazmi: no, the 1D array has exactly the number of items as the 2D array. – Cheers and hth. - Alf Oct 03 '14 at 04:39
  • 1
    2D indexing requires multiplication and addition, 1D indexing is just addition. – Barmar Oct 03 '14 at 04:39
  • But in this particular case, the loop will always execute 100 times? My question specifically relates to the fact that the amount of times I'm looping will always be the same, but whether accessing a 2D array structure will be faster/slower than accessing a 1D structure. – Daniel Oct 03 '14 at 04:39
  • So because of that indexing it would essentially make it slower? I guess this makes sense because I've read in so many places people always saying to flatten your data where possible, I guess this is probably the reason behind it. thank you. – Daniel Oct 03 '14 at 04:42
  • I don't see how this is a duplicate, in that question he is asking specifically about recalculating the indexes in a 1D array, although it might be similar its definitely not the same question. – Daniel Oct 03 '14 at 04:47
  • @Daniel: The recalculation is done by the compiler's emitted machine code for your code. So the *question* covers your question as well. The "has an answer there" added by SO machinery when we indicate **duplicate** is a bit overly optimistic in my view since I don't see a direct answer of your part of the question, the case where the 2D array is contiguous. But such an answer (you've alredy got some in the comments, but it really depends on optimization so you can only *measure*) belongs in the more general question, IMO. – Cheers and hth. - Alf Oct 03 '14 at 05:05
  • oh, the lowest voted answer, (http://stackoverflow.com/a/17260179/464581), at just 1 upvote, is the one that's most general. – Cheers and hth. - Alf Oct 03 '14 at 05:09

0 Answers0