2

I have an enum and a switch statement using some of the enum entries but not all and they are currently out of order too, i.e. I have the following:

enum prot_tun_stat_e    {
    STAT_A = 0,     
    STAT_B,     
    STAT_C, 
    STAT_D,
    STAT_E,
    STAT_F, //5
    STAT_G,
    STAT_H,
    STAT_I,
    STAT_Y,
    STAT_K,     //10
    STAT_COUNT      //must be last
} __attribute__((packed));

and then I have a switch using the following entries:

switch(var) {
case C:
break;
case D:
break
case F:
break
case G:
break
default
}

and I was wondering if I better rearranged the items in the enum to be C=1,D=2,F=3&G=4 ? Would that be more efficient?

Thanks, Ron

Platform: PowerPC, compiler diab

1
  • 1
    You want to know if testing var against the numbers 1, 2, 3 and 4 would be more efficient than testing it against the numbers 2, 3, 5 and 6? I would be very surprised if it made the tiniest bit of difference.
    – r3mainer
    Commented Nov 1, 2016 at 23:14

2 Answers 2

5

If the compiler can determine that the parameter to the switch statement is limited to a small number then it can create a jump table. This table will take up less room if the values are contiguous but the difference between 4 entries or the 10 required is unlikely to matter. (And note that 0-3 is a better range than 1-4 - although the compiler can deal with this by jumping to offset n - 1).

You can check the output of the compiler to see if a jump table is being created (assuming you can read assembly!). And of course the answer to all performance questions: profile it!

4

I can't talk about the diab compiler, because I'm not familiar with it, but an optimizing compiler will most likely create a jump table for a switch statement over an enum. So the order wouldn't matter. Having said that, you shouldn't worry about such trivial things. Correct me if I misunderstood your question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.