foreach is slower than for?
Stanislav Blinov
stanislav.blinov at gmail.com
Wed Sep 8 14:12:55 PDT 2010
I was wondering about it for some time:
void foreach_loop(int arr[100])
{
foreach(i,a; arr)
{
auto e = a;
}
}
void for_loop(int arr[100])
{
for (int i = 0; i < 100; ++i)
{
auto e = arr[i];
}
}
compiled with -O -release yields this:
.text.void main.foreach_loop(int[100]) segment
assume CS:.text.void main.foreach_loop(int[100])
void main.foreach_loop(int[100]):
push EBP
mov EBP,ESP
sub ESP,8
mov EAX,064h
lea ECX,8[EBP]
xor EDX,EDX
mov -8[EBP],EAX
mov -4[EBP],ECX
cmp -8[EBP],EDX
je L23
L1B: add EDX,1
cmp EDX,-8[EBP]
jb L1B
L23: mov ESP,EBP
pop EBP
ret 0190h
nop
nop
nop
.text.void main.foreach_loop(int[100]) ends
.text.void main.for_loop(int[100]) segment
assume CS:.text.void main.for_loop(int[100])
void main.for_loop(int[100]):
push EBP
mov EBP,ESP
xor EAX,EAX
L5: inc EAX
cmp EAX,064h
jb L5
pop EBP
ret 0190h
nop
.text.void main.for_loop(int[100]) ends
Without -O -release the difference is even greater
Is this normal? I mean, shouldn't the compiler optimize foreach a bit
more? Or is it that I simply misunderstand generated code?
More information about the Digitalmars-d
mailing list