Performance of C loops For Vs While Vs goto [duplicate]

青春壹個敷衍的年華 提交于 2019-12-23 18:49:53

问题


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?


回答1:


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.




回答2:


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).




回答3:


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.




回答4:


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.



来源:https://stackoverflow.com/questions/5518027/performance-of-c-loops-for-vs-while-vs-goto

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!