Jump to content
  • entries
    46
  • comments
    207
  • views
    39,693

For loop optimization


AggrorJorn

2,899 views

 Share

Today I learned a pretty basic but very usefull programming principle. It is about declaring multiple initialisers in a for loop. I am working with a mobile application and speed and memory are more of an issue than on computer right now. My application is finished when you look at its functionality and construction, but it has to be optimized.

 

Here is a narrowed down example of what I am doing:

 

for(int i = 0; i < veryLongArray.length(); i++)
{
 DoSomething(i);
}

This is very basic coding right here that can be found in many language.

 

 

What I didn't know is that you can declare multiple initialisers. It is very simple but has increased the speed of the for loop (which is pretty huge) immensly. This is how it looks now:

for(int i = 0, j = veryLongArray.length(); i < j ;i++)
{
 DoSomething(i);
}

By initialising the j variable at the start of the for loop, we can save a little time. Instead of checking the length every loop we can simply refer to the j variable. ofcourse you can store the length of the array outside the loop as well, but this is so much nicer. One catch though: If the length of the array is dynamicly changed during the loop, then you shouldn't be using this.

 

So simple, yet, I have never come accross it before.

  • Upvote 1
 Share

7 Comments


Recommended Comments

I have another little optimization for you.

Always use pre incrementing values where possible, like ++i instead of i++.

  • Upvote 1
Link to comment

So simple, yet, I have never come accross it before.

 

If you think about its very logical. You called each for iteration a function compared to call it once and save the result temporarly.

 

Another good optimization is for two dimensional array, take care of your traversing order e,g.

// creation
unsigned char** myarray = new unsigned char*[1024];
for (int i = 0; i < 1024; ++i)
{
   myarray[i] = new unsigned char;
}

// update
for(int y = 0; y < 1024; ++y)
{
for(int x = 0; x < 1024; ++x)
{
 myarray[y][x] = 0;  // swapping x and y results in decrease/increase of nearly 50% on my system .... its because cache misses and miss prediction of cpu.
}
}

  • Upvote 1
Link to comment
Guest Red Ocktober

Posted

i have a hard enough time keeping track of a single iterator...

 

:)

 

--Mike

Link to comment

The i++ version creates a temporary copy of i, increases i by one and returns the copy.

The ++i version just increases the value of i by one and returns it.

Link to comment
Guest
Add a comment...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...