faster than switch statement?

09 Jul 2010

I have a finite state machine coded barely like this:

while(1){
 switch(core_state)
{ 
 case IDLE:
 //bla, bla, bla
 break;

 case RUN:
 //bla, bla, bla
 break;
}
} 
It takes about 400ns to go through the SWITCH statement and branch into a certain state. I don't have the assembly code to compare with. Is it possible that IF-ELSE statement is faster than SWITCH?

I'd like to speed it up 2 times at least. How shall I do it?

Thanks.

 

 

13 Jul 2010

Dunno about this compiler: generally switches are faster than if/else if/.../else statment as swtiches compile to jump tables rather than the sequence of compare & branch that ifs compile to.

A simple if/else could be faster than a switch, esp if the likely result is dealt with in the if condition rather than the else condition. Try it & see.

I'm new to this mbed thing so I dunno about optimisation settings in the compiler - have alook at them.

If it's still not fast enough for you then you're going to have to get into assembler & get creative with the pipeline. Or move to a faster core.