C / C ++:是GOTO快于while和for? [英] C/C++: is GOTO faster than WHILE and FOR?
问题描述
我知道,那人人都恨GOTO,没有人推荐它。但是,这不是问题的关键。我只是想知道,这code是最快的:
-
的
转到
循环INT I = 3;
循环:
的printf(东西);
如果( - 我)转到循环; -
的
,而
循环INT I = 3;
当我 - ) {
的printf(东西);
} -
的
为
循环的for(int i = 3;我;我 - ){
的printf(东西);
}
一般来说,为
和,而
循环被编译为同样的事情转到
,因此通常不会有所作为。如果你有你的疑惑,你可以随意尝试所有这三个,看看这需要更长的时间。奇怪的是,你将无法衡量的差异,即使你循环十亿倍。
如果你看一下<一个href=\"http://stackoverflow.com/questions/2288856/when-implementing-an-infinite-loop-is-there-a-difference-in-using-while1-vs-fo/2288893#2288893\">this回答,你会看到,编译器可以生成完全相同的code为为
,,而
和转到
(只有在这种情况下,有没有条件)。
I know, that everybody hates GOTO and nobody recommends it. But that's not the point. I just want to know, which code is the fastest:
the
goto
loopint i=3; loop: printf("something"); if(--i) goto loop;
the
while
loopint i=3; while(i--) { printf("something"); }
the
for
loopfor(int i=3; i; i--) { printf("something"); }
Generally speaking, for
and while
loops get compiled to the same thing as goto
, so it usually won't make a difference. If you have your doubts, you can feel free to try all three and see which takes longer. Odds are you'll be unable to measure a difference, even if you loop a billion times.
If you look at this answer, you'll see that the compiler can generate exactly the same code for for
, while
, and goto
(only in this case there was no condition).
这篇关于C / C ++:是GOTO快于while和for?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!