For loop Optimization

We always wonder about for loop optimization, lets get into it.

Look at the following nested for loop

Now look at this

Does both of them look similar?
I guess your answer would be YES as both them execute any code 1000 times, but actually they are not.
There are many differences in them and lets discuss each of them.

1- Assignment:

First loop uses Assignment operator (=)  101 times. How?
  • i=0 is assigned 1 time and j=0 is assigned 100 times i.e. total 101 times.
Now for Second loop Assignment operator (=) is used 11 times. How?
  • i=0 is assigned 1 time and j=0 is assigned 10 times i.e. total 11 times.
Now can you see the difference? 

2- Comparison:

First loop uses Conditional operator ( < ) 1021 times. How?
  • i<10 will be compared 11 times( for i=11 condition will be checked if i<10 so 11 times ) and j<100 will be compared 1010 times  ( j<101 will be compared for 10 times i.e. 10*101=1010 times) so total 11+1010=1021 times.
Now for Second loop ( < ) operator is used 1201 times. How?
  • i<100 will be compared 101 times and for each i, j<10 is compared 11 times i.e. 100*11=1100 times, so total 101+1100=1201 times.
Still not clear?

3- Increment:

In first loop increment operator (++) is used 1010 times. How?
  • i++ is done 10 times and j++ is done 10*100=1000 times i.e. total 1010 times.
In second loop (++) is used 1100 times. How?
  • i++ is done 100 times and j++ is done 100*10=1000 times i.e. total 1100 times.
Now I think you can actually differentiate between different for loops and hence you can yourself do the “For loop optimization”.
For any query please comment.

1 Comment

  1. Both loops create unnecessarily many temporaries. Why? ’cause you thought about premature optimization of for loops, but did not remember the simple thing that even beginners get tought: i++ first returns a copy of i (the temporary), then increments i.
    Why you no use ++i? this would first increment i, then return it. No copy, no temporary.

Leave a Reply