For loop optimization
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.
- 1
7 Comments
Recommended Comments