Why infinite loops are faster than finite loops?

Виталий Фадеев vital.fadeev at gmail.com
Sun Jun 21 08:41:29 UTC 2020


On Saturday, 20 June 2020 at 21:11:57 UTC, tastyminerals wrote:
> I am not sure that this is a question about D or a more general 
> one. I have watched this nice presentation "Speed Is Found In 
> The Minds of People" by Andrei: 
> https://www.youtube.com/watch?v=FJJTYQYB1JQ&feature=youtu.be?t=2596 and on 43:20 he says that "push_heap" is slow because of structured loops and finite for (throughout the presentation Andrei shows algorithm examples with infinite loops). I wonder why is that? Is it because the finite loop needs to keep track of the number of iterations it performs? Wouldn't the compiler optimize it better than the infinite one because it knows the number of iterations the for loop needs?

I think the Answer depended from the Task.

I think Alexandrescu is joking. :)
"Always* Use Infinite Loops. (*Except in most cases)" :)


For code:

     di = "String";
     needle = "A";
     ascan = di.ptr;

     for( int cx = di.length; cx != 0; cx--, scan++ )
     {
         if ( *scan == neelde )
             goto found;
     }
     return;

     found:
         // Found!

in best case generated instructions will be like this:

             CLD                     ;Scan string in forward 
direction
             MOV     AL,'A'          ;Scan for 'A'
             LEA     DI, STRING      ;Address to start scanning at
             MOV     CX,100          ;Scanning 100 bytes
     REPNE   SCASB                   ;   ...and scan it
             JE      found           ;
             JMP     exit            ;
     found:
             DEC     DI              ;Back up DI to point to the 
'A'

...var CX translated to register CX.
...pointer translated to register DI.
...needle translated to register AX.
All in registers!


What asm-code generaged for C-code showed by Alexandrescu ?



More information about the Digitalmars-d-learn mailing list