Lookup table vs switch in C embedded software

前端 未结 6 2146
无人及你
无人及你 2020-12-05 09:28

In another thread, I was told that a switch may be better than a lookup table in terms of speed and compactness.

So I\'d like to understand the

6条回答
  •  猫巷女王i
    2020-12-05 10:16

    msc's answer and the comments give you good hints as to why performance may not be what you expect. Benchmarking is the rule, but results will vary from one architecture to another, and may change with other versions of the compiler and of course its configuration and options selected.

    Note however that your 2 pieces of code do not perform the same validation on state:

    • The switch will gracefully do nothing is state is not one of the defined values,
    • The jump table version will invoke undefined behavior for all but the 2 values FUNC1 and FUNC2.

    There is no generic way to initialize the jump table with dummy function pointers without making assumptions on FUNC_COUNT. Do get the same behavior, the jump table version should look like this:

    void fsm(int state) {
        if (state >= 0 && state < FUNC_COUNT && lookUpTable[state] != NULL)
            lookUpTable[state]();
    }
    

    Try benchmarking this and inspect the assembly code. Here is a handy online compiler for this: http://gcc.godbolt.org/#

提交回复
热议问题