relative speed of incremention syntaxes (or "i=i+1" VS "i+=1")

Chris Angelico rosuav at gmail.com
Sun Aug 21 19:37:45 EDT 2011


2011/8/22 Andreas Löscher <andreas.loescher at s2005.tu-chemnitz.de>:
> How would such an jump table work to behave the same liek a
> switch-case-statement?

If your switch statement uses a simple integer enum with sequential
values, then it can be done quite easily. Take this as an example:

        switch (argc)
        {
            case 0: printf("No args at all, this is weird\n"); break;
            case 1: printf("No args\n"); break;
            case 2: printf("Default for second arg\n");
            case 3: printf("Two args\n"); break;
            default: printf("Too many args\n"); break;
        }

I compiled this using Open Watcom C, looked at the disassembly, and
hereby translate it into pseudocode (I'll email/post the full 80x86
disassembly if you like):

1) Check if argc > 3 (unsigned comparison), if so jump to default case.
2) Left shift argc two places, add a constant offset, fetch a pointer
from there, and jump to it - that's the jump table. One JMP statement.
3) Code follows for each case.

Incidentally, the Open Watcom compiler actually turned several of the
cases into offset-load of the appropriate string pointer, and then a
jump to the single call to printf. The fall-through from 'case 2' to
'case 3' works fine, although it means that 'case 2' has to be
de-optimized from that one simplification.

This type of optimization works best when the case values are
sequential. (If I remove the 'case 0', the compiler decrements argc
and proceeds to continue as above.) Otherwise, the jump table has to
have a lot of copies of the "default" pointer.

Chris Angelico



More information about the Python-list mailing list