wal*_*ali 1 language-agnostic compiler-construction loops for-loop while-loop
在我的算法设计和分析讲座中,讲师说for循环将花费更少的时间然后循环用于以下样本算法.
1. for(int i=0;i<5;i++)
{
2. print(i);
}
1. int i=0;
2. while(i<5)
{
3. print(i);
4. i++;
}
Run Code Online (Sandbox Code Playgroud)
他说,编译器会读取1. of for while 5次line 2. 4次因此总时间5 + 4 = 9但是在while循环的情况下.编译器将读取1. 1次,2.5次,3次4次,4次4次.因此总时间1 + 5 + 4 + 4 = 14时请告诉我这是对的.for循环比while循环更快吗?
谢谢.
至少在MSVC 16(VS 2010)中,代码在两种情况下几乎相同:
对于
; 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
Run Code Online (Sandbox Code Playgroud)
而
; 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
Run Code Online (Sandbox Code Playgroud)