While loops are more efficient than loops

I was told that the while loop is more efficient than the for loop. (C / C ++) This seemed reasonable, but I wanted to find a way to prove or disprove it.

I tried three tests using similar code snippets. Each of them contains nothing but a for or while loop with the same output:

  • Compilation time is about the same
  • Lead Time - Same
  • Compiled for Intel assembly code and compared - the same number of lines and almost the same code

Should I try something else, or can someone confirm one way or another?

+5
source share
3 answers

All loops follow one pattern:

{ // Initialize LOOP: if(!(/* Condition */) ) { goto END } // Loop body // Loop increment/decrement goto LOOP } END: 

For this, two loops are the same:

 // A for(int i=0; i<10; i++) { // Do stuff } // B int i=0; while(i < 10) { // Do stuff i++; } // Or even int i=0; while(true) { if(!(i < 10) ) { break; } // Do stuff i++; } 

Both are converted to something similar:

 { int i=0; LOOP: if(!(i < 10) ) { goto END } // Do stuff i++; goto LOOP } END: 

Unused / inaccessible code will be deleted from the final executable file / library.

Do-while loops skip the first conditional check and remain as an exercise for the reader. :)

+3
source

Of course, LLVM converts all types of loops into a consistent form (if possible, of course). Thus, if you have the same functionality, it doesnโ€™t really matter if you use for , while , do-while or goto to form a loop, if it received the same initialization, the exit condition and update and body, it will give same machine code.

This is difficult to do in the compiler if it was done early enough during optimization (therefore, the compiler still understands what is actually being written). The goal of this โ€œmake all loops equalโ€ is that you only need one way to optimize loops, instead of having one for while-loops, one for for-loops, one for do-while and one for "any other loops "".

This is not guaranteed for ALL compilers, but I know that gcc / g ++ also generates almost identical code no matter what the contour is built, and from what I saw, Microsoft also does the same.

+1
source

The C and C ++ compilers actually convert high-level C or C ++ codes to assembler codes, and in the assembly we do not have while or for loops. We can only check the condition and move to another place.

Thus, the performance of a for or while depends heavily on how strong the compiler is for optimizing codes.

This is a good article on code optimization:

http://www.linux-kongress.org/2009/slides/compiler_survey_felix_von_leitner.pdf .

+1
source

Source: https://habr.com/ru/post/1240289/


All Articles