#### Archived

This topic is now archived and is closed to further replies.

# Loops

This topic is 5732 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

hypothetical: Would

long foo=0
long bar=0

long array[10000][5]= {3,6,2,6,8}

for (foo=0; foo<=9999; foo++)
{
for (foo=0; foo<=5; foo++)
{
array[foo][bar]++;
}
}

be faster than

long foo=0
long bar=0

long array[10000][5]= {3,6,2,6,8}

for (foo=0; foo<=9999; foo++)
{
array[foo][0]++;
array[foo][1]++;
array[foo][2]++;
array[foo][3]++;
array[foo][4]++;
}

Assuming the situation is rigorously the same, but a little bit more complicated. Would the later be much faster?

##### Share on other sites
Theoretically the second should be faster. Also, I think this might be a little faster than the first example you gave.

  long foo=0;long bar=0;long array[10000][5]= {3,6,2,6,8};for (bar=0; bar<=5; bar++) {  for (foo=0; foo<=9999; foo++) {      array[foo][bar]++;  }}

All I did was switch the inner and outer loops. Putting the loop with more iterations as the inner loop should be faster, I think. Also it might be possible to write it quite a bit faster using pointers rather than indexes into a 2D array. Maybe like this.

  long array[10000][5]= {3,6,2,6,8};long * p, * end = array + 49999;for (p=array; p != end; p++)    (*p)++;}

[edited by - Russell on April 2, 2003 6:00:16 PM]

##### Share on other sites
foo<=5;

This goes to 5.. meaning that it''ll try to access index [5] which is illegal.

##### Share on other sites
use < not <=, and yes the second case would be marginally faster, depending on what goes on inside the second loop.

It would also be faster to flip it around:
for(int j=0; j<5; ++j)   for(int i=0; i<10000; ++i)      stuff();

##### Share on other sites
Careful everyone,

array [ a ][ b ] implies a-rows by b-colums.

the b is direct indexing, so your loop should be (optimized):

for(a...) {
for(b...) {
array[ a ][ b ] = xxx;
};
};

and not the other way around like this:

for(b...) {
for(a...) {
array[ a ][ b ] = xxx;
};
};

This second example is an order of magnitude slower.

www.cppnow.com

[edited by - superdeveloper on April 2, 2003 11:58:44 PM]

##### Share on other sites
Don't forget about loop inversion*.. some machines are faster with decrementing and comparing with zero than incrementing and comparing with a certain maximum. Text both loops with your machine to see which runs faster.

    foo = 10000while (--foo){   array[foo][4]++;   array[foo][3]++;   array[foo][2]++;   array[foo][1]++;   array[foo][0]++;}

* "C Unleashed" by SAMS is a great book.

(silencer)

[edited by - -silencer- on April 3, 2003 2:43:44 AM]

1. 1
2. 2
3. 3
Rutin
15
4. 4
5. 5

• 9
• 9
• 11
• 11
• 23
• ### Forum Statistics

• Total Topics
633677
• Total Posts
3013284
×