Archived

This topic is now archived and is closed to further replies.

vicviper

"switch / case" command performance

Recommended Posts

vicviper    130
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

Share this post


Link to post
Share on other sites
Monder    993
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]

Share this post


Link to post
Share on other sites
Guest Anonymous Poster   
Guest Anonymous Poster
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.

Share this post


Link to post
Share on other sites
quorn    145
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.

Share this post


Link to post
Share on other sites
vicviper    130

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?

Share this post


Link to post
Share on other sites
Anon Mike    1098
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.

Share this post


Link to post
Share on other sites
Zipster    2365
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.

Share this post


Link to post
Share on other sites
Feidias    92
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

Share this post


Link to post
Share on other sites