For Loop vs While Loop – Performance in C++ and Java

c++javaperformance

Which is better for performance? This may not be consistent with other programming languages, so if they are different, or if you can answer my question with your knowledge in a particular language, please explain.

I will be using c++ as an example, but I would like to know how it works in java, c, or any other mainstream languages.

int x = 0;
 while (x < 10) {
    cout << x << "\n ";
    x++;
  }

VS

for ( int x = 1; x < 10; x++)   
 cout << x << "\n ";

Which one performs better? If it is the for loop, then lets say that there was an integer already declared that we could use in the while loop increment, that we didn't need to create just for the while loop?

example:

int age = 17; //this was made for something else in the code, not a while loop. But fortunately for us, our while loop just so happened to need the number 17.

 while (age < 25) {
        cout << age << "\n ";
        age++;
      }

Would this instance make the while loop a better choice than creating a for loop? And I have seen questions somewhat similar to this, but I do not believe that this is a duplicate, or any of the answers on those other questions answered my question.

I want an explanation on this question, explaining if it is compiler specific, how it works, or whatever is a good answer to this question.

Best Answer

All sensible compilers should compile equivalent loops to identical assembly / IL code involving branches and jumps. (at least with optimizations enabled)

Related Question