"switch / case" command performance

Started by
7 comments, last by vicviper 19 years, 10 months ago
what is faster? a "switch/case" table, or a list of "if/else if" list? I ask because I have to place a lot of comparisons in a very critical loop. thanks in advance
Advertisement
If you're testing a variable against many constants a swith case is likely to be faster, as well as it being cleaner code.

[edited by - Monder on May 26, 2004 7:19:43 AM]
Switch statements are often compiled into a series of if/else. There is, however, one great optimization some compilers can do in some cases, the jump table.
if they are based on the type of an object your design is probably wrong.

move the type specific behaviour into the class and use a virtual function.

i know, i''m off at a tangent.

ok, "switching" to a "switch/case" architecture.

which would be the conditions in which the compiler would use a jump table instead of a if/else tree?

maybe, the use of enumerated values in the case params?
I *really* doubt that either way is going to make anything vaguely approaching a noticable difference in a real app. Write your code so it''s clear and worry about irrelevant optimizations once you can profile working code.
-Mike
Good analysis, even if the application there is silly.
E8 17 00 42 CE DC D2 DC E4 EA C4 40 CA DA C2 D8 CC 40 CA D0 E8 40E0 CA CA 96 5B B0 16 50 D7 D4 02 B2 02 86 E2 CD 21 58 48 79 F2 C3
quote:Original post by vicviper

ok, "switching" to a "switch/case" architecture.

which would be the conditions in which the compiler would use a jump table instead of a if/else tree?

maybe, the use of enumerated values in the case params?

If the size of the range of your constants (max - min) is within a certain boundary, and you have more than just a couple of cases that would warrant a jump table, then the compiler usually goes ahead and makes one. But it''s compiler-specific, and you really can''t be guaranteed of anything.
quote:Original post by Anon Mike
Write your code so it''s clear and worry about irrelevant optimizations once you can profile working code.


In some cases you can avoid using either switch-case or if(-else) by using data instead of code. If you have seen the source code of Dungeon Crawl you can see why avoiding switch-cases can be a good thing

This topic is closed to new replies.

Advertisement