循环对While循环 [英] For Loop vs While Loop
问题描述
在我的设计和分析
算法的讲座中,教师表示for循环将花费更少的时间,而循环则用于下面的示例algo。
In my lecture of Design and Analysis of Algorithms the instructor said the for loop will take less time then while loop for the following sample algo.
1. for(int i=0;i<5;i++)
{
2. print(i);
}
1. int i=0;
2. while(i<5)
{
3. print(i);
4. i++;
}
他说编译器会读取1。 2. 4倍于总时间5 + 4 = 9
但是在while循环的情况下。编译器将读取1次,1次,2。 5次,3次4次,4次4次。因此总时间1 + 5 + 4 + 4 = 14时
请告诉我是这个权利。是for循环比while循环快吗?
He said that the compiler will read the 1. of for while 5 times line 2. 4 times thus total time 5+4=9 But in the case of while loop. The compiler will read the 1. for 1 time,2. for 5 time, 3 for 4time and 4. for 4 time. Thus total time 1+5+4+4 = 14time Please tell me is this right. Is for loop is faster than while loop?
谢谢。
推荐答案
至少对于MSVC 16(VS 2010),代码在两种情况下都大致相同:
At least with MSVC 16 (VS 2010) the code is pretty much the same in both cases:
用于
; Line 5
xor esi, esi
$LL3@main:
; Line 6
push esi
push OFFSET ??_C@_03PMGGPEJJ@?$CFd?6?$AA@
call _printf
inc esi
add esp, 8
cmp esi, 5
jl SHORT $LL3@main
while
; Line 4
xor esi, esi
$LL2@main:
; Line 6
push esi
push OFFSET ??_C@_03PMGGPEJJ@?$CFd?6?$AA@
call _printf
; Line 7
inc esi
add esp, 8
cmp esi, 5
jl SHORT $LL2@main
在我的Subversion存储库中代码。
Code in my Subversion repository.
这篇关于循环对While循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!