Fast switch statement

bearophile bearophileHUGS at lycos.com
Wed Apr 3 18:30:18 PDT 2013


Steve Kucera:

> I am using DMD 2.062 on Windows 7 64-bit.
>
> I am writing performance critical functions that need switch 
> statements to use an indirect jump table... current I'm 
> analysing the assembly dump, and the code is compiled to nested 
> ifs instead. This happens with switch and final switch. Is 
> there any way to force the compiler to use a jump table?

What kind of switch do you have? Are you switching on strings?

Here I am not seeing nested ifs, this is efficient enough:


import core.stdc.stdio: puts;
void main(string[] args) {
     switch (args.length) {
         case 0: puts("0"); break;
         case 1: puts("1"); break;
         case 2: puts("2"); break;
         case 3: puts("3"); break;
         default: puts("default"); break;
     }
}




main:
L0:     push    EAX
         push    EBX
         mov EBX,0Ch[ESP]
         cmp EBX,3
         push    ESI
         ja  L53
         jmp dword ptr FLAT:_DATA[018h][EBX*4]

         mov ESI,offset FLAT:_DATA
         push    ESI
         call    near ptr _puts
         add ESP,4
         jmp short   L61

         mov EDX,offset FLAT:_DATA[4]
         push    EDX
         call    near ptr _puts
         add ESP,4
         jmp short   L61

         mov ECX,offset FLAT:_DATA[8]
         push    ECX
         call    near ptr _puts
         add ESP,4
         jmp short   L61

         mov EAX,offset FLAT:_DATA[0Ch]
         push    EAX
         call    near ptr _puts
         add ESP,4
         jmp short   L61

L53:        mov EBX,offset FLAT:_DATA[010h]
         push    EBX
         call    near ptr _puts
         add ESP,4

L61:        pop ESI
         xor EAX,EAX
         pop EBX
         pop ECX
         ret


Bye,
bearophile


More information about the Digitalmars-d-learn mailing list