Possible Duplicate:
C/C++: is GOTO faster than WHILE and FOR?
I know this has been asked for many times, but I never got an answer which satisfies me by googling.
I read somewhere that every loop(开发者_运维知识库for/while/do-while/untill) will be eventually be converted to goto statements internally, Is that True?
If not, Which is the best loop to use as per the performance wise? Let me know if anybody knows?
The correct answer is to learn enough assembly in order to read through your compiler's generated code.
However, these micro-optimizations usually don't matter (except for very specific areas).
They say "converted to goto statements internally" as meaning machine/assembly does not have a notion of loops, just compare/jump to label
instructions which would equate to if/goto
.
Any loop construct you write will be reduced to this.
With any decent compiler, this won't make any difference at all. Each type of loop is likely to result in comparable assembly code.
It's best to use a type of loop that most naturally expresses what you want to achieve; this also makes it likely that the compiler can optimize it well.
The compiler translates all your source code into the assembler language for the target processor. The assembler language is very low level and does not have constructs like for
and while
. The assembler language has uses jump statements which are equivalent to goto
in your high level language program.
Performance wise it should not really matter which loop construct you use.
If you want to see and compare the generated assembler code you can invoke gcc like so: gcc main.c -S -O2
and take a look at the generated main.S
file which now contains the assembler code for your program.
Make sure to include the -O2
or -O3
optimization flags because comparing code which has been build without optimizations turned on does not make much sense.
精彩评论