switch versus if

Are "switch" statements faster to process than "if / else" statements?

RudiAhlers:
Are “switch” statements faster to process than “if / else” statements?

I haven’t looked at the assembly code, but I’d be surprised if there were significant differences. It’s probably six and a half of one and a dozen of the other :wink:

RudiAhlers:
Are "switch" statements faster to process than "if / else" statements?

This seems a strange Thread in which to ask that question, but never mind.

This is the sort of question that can be answered more quickly by writing two small sketches than by asking questions here. The Arduino is a wonderful system for experimenting and learning by doing.

And I don't know the answer.

...R

Robin2:
This seems a strange Thread in which to ask that question, but never mind.

Thread split.

Are "switch" statements faster to process than "if / else" statements?

There is an optimization that allows certain switch statements to be significantly faster. As far as I know, the compiler that ships with Arduino 1.0.x does not perform the optimization.

RudiAhlers:
Are "switch" statements faster to process than "if / else" statements?

It depends on how you arrange the if-else or switch-case logic.
Where you make the splits, cut exceptions from what fits an algorithm, apply Occam's razor or not makes or breaks the decision tree.

There are threads and a section in the Playground on optimizations, with optimizations on those that wring cycles out of processes to get the best. Looking in those I see amazing tricks using different structures but also some are puzzles that take a long time and sketch experiments to see how they work at all.

If you plan to expand code later on, switch-case is usually more flexible.
The places to count cycles are the ones that run a lot or run in very close margins.

Thanks.

If you have the patience to bring over one more post it would be very nice.

...R

I've known people before who would say that if speed really matters, use assembler.

AVR has a lot of general registers compared to older 8 bit chips. When you can get most of your algorithm into those, you can do a high percentage of 1 cycle operations. The coding effort is more than with C, and that's understatement.

There's a forum for people who like to do that. Not a beginner friendly place from what I hear. AVRfreaks.