Best infinite loop [duplicate]
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?
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.
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
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?
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.
Same thing. compiler will translate it to a single JMP instruction.
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.
精彩评论