C / C ++:是GOTO快于while和for? [英] C/C++: is GOTO faster than WHILE and FOR?

查看:232
本文介绍了C / C ++:是GOTO快于while和for?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道,那人人都恨GOTO,没有人推荐它。但是,这不是问题的关键。我只是想知道,这code是最快的:


  1. 转到循环

      INT I = 3;
    循环:
    的printf(东西);
    如果( - 我)转到循环;


  2. ,而循环

      INT I = 3;
    当我 - ) {
        的printf(东西);
    }


  3. 循环

     的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:

  1. the goto loop

    int i=3;
    loop:
    printf("something");
    if(--i) goto loop;
    

  2. the while loop

    int i=3;
    while(i--) {
        printf("something");
    }
    

  3. the for loop

    for(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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆