Main Site Documentation

Switch statement compilation details


#1

Hello,

I am attempting to implement a switch statement to call the correct function upon receiving an external command. I have about 15 commands and I thought a switch statement would be appropriate.

I figured I would get the best performance if I built the switch statement from top to bottom by prioritizing the expected frequency and desired speed of processing for the different messages.

What I found instead is that the IL seems to suggest that it is the actual byte value of the command’s opcode (the variable about which I switch) that dictates the order of processing. I.E. command 0xA1 will be checked against before 0xA2. Assigning new values to the commands would require an update to already released software and is not the solution I want to jump to.

I’m writing in Netmf 4.3 using VS 2013. Is there a way I can command the compiler to order my switch cases in the way I desire without swapping my switch for a less pretty if-else chain?


#2

Try replacing the switch with a series of if/then/else statements arranged in the order of your switch statements.


#3

lol except that’s what he didn’t want :slight_smile:

:wink:

But seriously - have you tested the benefit of doing anything here versus letting the compiler deal with this stuff? If this kind of optimisation is make-or-break stuff, maybe interpreted languages with GC and non-deterministic timing isn’t the right tool?


#4

Thanks for the suggestion. This will be my course of action if I cannot achieve control of the switch statements execution. I just think I would like to maintain a switch for readability.


#5

No I have not actually measured any benefit. And a real-time environment would without a doubt be better… if it weren’t for the fact that I’m the sole programmer and a beginner at that. There is no reason that netmf can’t handle my app even though it isn’t perfectly suited.

I just thought if there was something like

#pragma do-it-my-way 

it would be sweet for a small optimization that lets me keep the source code looking the way I want. Of course, I would then benchmark my optimization vs. the compiler’s default.

It’s not make or break.


#6

If the command codes are in a sequential order, then you could have an array of delegates.