foreach is slower than for?

Tomek Sowiński just at ask.me
Wed Sep 8 14:26:10 PDT 2010


Dnia 08-09-2010 o 23:12:55 Stanislav Blinov <stanislav.blinov at gmail.com>  
napisał(a):

> 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?

Yes, it should; that was the point of having foreach in the language:
http://www.d-programming-language.org/faq.html#foreach

I think it's just that there's always plenty of more urgent things with  
DMD.


Tomek


More information about the Digitalmars-d mailing list