Best infinite loop [duplicate]

妖精的绣舞 提交于 2020-01-12 08:10:22

问题


Possible Duplicate:
while (1) Vs. for (;;) Is there a speed difference?

Hi,

Which is better,faster and more optimized way to implement infinite loop - for(;;) or while(1)? and why?


回答1:


In any normal compiler, there should be absolutely no difference. For example, here's what LLVM-clang generates (with the -O3 flag) for while (1) {}:

    .file   "test.c"
    .text
    .globl  main
    .align  16, 0x90
    .type   main,@function
main:
    pushl   %ebp
    movl    %esp, %ebp
    .align  16, 0x90
.LBB0_1:
    jmp .LBB0_1

Note the jmp .LBB0_1 part, which is the actual infinite loop. For the for (;;) kind, it generates absolutely the same code.

You can also try with other compilers for fun, but it's best just stop worrying about it.


OK, I just had to try with gcc as well:

    .file   "test.c"
    .text
.globl main
    .type   main, @function
main:
    pushl   %ebp
    movl    %esp, %ebp
.L2:
    jmp .L2



回答2:


I prefer for(;;) because it doesn't test anything and semantically this is what you mean. It doesn't make so much sense to keep testing if 1 is true. However any professional C programmer should immediately recognize both idioms as both are used.

In terms of actual performance there should be no difference. The compiler will optimize away the test.

I tried testing both to see which is faster but neither of them has completed yet.




回答3:


I would argue neither is more optimized, as neither will accomplish the task of looping infinitely in any measurable amount of time.

Is it really possible to reach infinity more or less efficiently?




回答4:


In theory, a completely naive compiler could store the literal '1' in the binary (wasting space) and check to see if 1 == 0 every iteration (wasting time and more space).

In reality, however, even with "no" optimizations, compilers will still reduce both to the same. They may also emit warnings because it could indicate a logical error. For instance, the argument of while could be defined somewhere else and you not realize it's constant.




回答5:


Same thing. compiler will translate it to a single JMP instruction.




回答6:


This is my opinion (no research done):

When debugging code as I step through it, for for loops it makes me go to all three parts the first time, then two the rest of the iterations. However, the while loop only has one. Just a thought.



来源:https://stackoverflow.com/questions/3505755/best-infinite-loop

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