Welcome, Guest. Please Login or Register.  • Help
SMF Underground
+ SHMUP-DEV » SHMUP DEV FORUMS » Assistance
|-+ Case Statement VS If Statement

Pages: [1]   Go Down
0 Members and 1 Guest are viewing this topic. Topic Tools  
Read December 31, 2005, 12:14:02 AM #0
Matt McFarland

Case Statement VS If Statement

What's the difference?  I seem to get everything done with IF statements and with no need for CASE statements?  Was CASE just there for user preference?


<a href="http://www.mattmcfarland.com/flash/myFlashSig.swf" target="_blank">http://www.mattmcfarland.com/flash/myFlashSig.swf</a>
Offline  
Read December 31, 2005, 12:27:19 AM #1
Olofson

Re: Case Statement VS If Statement

Well, implementation details differ between languages, but in general, switch/case/... statements turn into some form of jump tables or similar, when this results in faster code than code corresponding to an if chain. So, switch/case/... may be faster, and potentially very much so if the list of cases is long. (Which usually doesn't really matter unless you're in an inner loop, such as the instruction decoder of a virtual machine or something.)

Again slightly language dependent, but the most important difference is that a switch/case/... statement can be more to the point, easier to read and more solid than the corresponding if chain. ("Solid", as in, "doesn't break as easy when you mess around with the code.") Some languages also make the switch/case/... aware of enumerated types and the like, and can throw warnings or errors if possible values are unhandled. This can help a lot in avoiding strange bugs when you extend the code.


//David
Offline  
Read December 31, 2005, 01:00:28 AM #2
oNyx

Re: Case Statement VS If Statement

Yea, it may be turned into a jump table. Rule of thumb... if you need more than 3 if thingies and the same can be written as switch use it.
Offline  
Read December 31, 2005, 01:06:26 AM #3
paladin

Re: Case Statement VS If Statement

case = deeper condition checking


needs more particles...
Offline  
Read December 31, 2005, 07:21:31 PM #4
Taiphoz

Re: Case Statement VS If Statement

I would use case by default cos like they said already is faster.

Unless is a single if then statment.

As a rule of thumb as again said above you should really use case statements as much as possible, a lot of people use them to control the flow of their game much like this..

state = alive

select state
  case alive : do alive stuff
  case dead : do dead stuff
 case landing : do landing stuff
end select

etc...

Its also very good for controlling case based AI which is something I try to use a lot.


Offline  
Read December 31, 2005, 07:42:05 PM #5
Olofson

Re: Case Statement VS If Statement

I would use case by default cos like they said already is faster.

Unless is a single if then statment.

Well, they may be a lot faster regardless in interpretted and VM based languages, as things scale very differently in those, compared to native code. In compiling languages though, an "optimal" switch is usually at least one range check (so you don't index outside the table) and one jump-through-table of some sort. I think two or maybe even three ifs will generally be faster than a switch/case.

Anyway, if it actually really matters, don't assume anything! Benchmark. Computers are complex things these days, and it's easy to slow things down when you think you're optimizing... Grin


//David
Offline  
Read December 31, 2005, 10:53:20 PM #6
Taiphoz

Re: Case Statement VS If Statement

I would use case by default cos like they said already is faster.

Unless is a single if then statment.

Well, they may be a lot faster regardless in interpretted and VM based languages, as things scale very differently in those, compared to native code. In compiling languages though, an "optimal" switch is usually at least one range check (so you don't index outside the table) and one jump-through-table of some sort. I think two or maybe even three ifs will generally be faster than a switch/case.

Anyway, if it actually really matters, don't assume anything! Benchmark. Computers are complex things these days, and it's easy to slow things down when you think you're optimizing... Grin


Yeah thats very true, just when you think your 5 hours worth of code tweaks are about to give you an extra 200ms a tic you run it to find out that it sucks ass and you have just wasted 5 hours. Iv been there done that.

I now test limited code in small parts to limit the amount od damage and time wasted if the results are not what I expect.


Offline  
Read January 01, 2006, 11:50:41 AM #7
Nexic

Re: Case Statement VS If Statement

It has a fair bit of use in a situation like this:

Switch moo

Case 1:
moo = 2

Case 2:
EatCheese()

Now the if equivilent:


If moo = 1 then moo = 2
if moo = 2 then EatCheese()

In the first example moo will be set to 2, but won't run EatCheese(). In the second moo will be become 2 and instantly EatCheese(). Now if you don't wan't EatCheese() to be run immediately after moo is set to 2, then you would need to use case. One could argue that you could swap the if's around, but with more complex situations this begins to get hard and will make your code look incredibly messy.

Offline  
Read January 01, 2006, 04:06:52 PM #8
Taiphoz

Re: Case Statement VS If Statement

It has a fair bit of use in a situation like this:

Switch moo

Case 1:
moo = 2

Case 2:
EatCheese()

Now the if equivilent:


If moo = 1 then moo = 2
if moo = 2 then EatCheese()

In the first example moo will be set to 2, but won't run EatCheese(). In the second moo will be become 2 and instantly EatCheese(). Now if you don't wan't EatCheese() to be run immediately after moo is set to 2, then you would need to use case. One could argue that you could swap the if's around, but with more complex situations this begins to get hard and will make your code look incredibly messy.



you could have used a nested IF to overcome that, but you are correct, and things like this can be coded late at night when your not 100% clear, blurry eyed etc.. so yeah case/switch is the way to go.


Offline  
Read January 01, 2006, 08:20:23 PM #9
tesuji

Re: Case Statement VS If Statement

Surely just a simple else if would've worked in that example ? :

if moo = 1
    moo = 2
else if moo=2
    EatCheese()
end if

although I do agree case is generally more readable especially when you've got a long list of conditions based on the same variable. I still use if statements on the most part myself but that's just because I'm switching between lots of languages all the time and the case implementation does seem to vary a fair bit.
Offline  
Read January 02, 2006, 08:02:59 AM #10
TheColonial

Re: Case Statement VS If Statement

Hi All,

Just signed up to the forums - looks very nice!

I just thought I'd mention something here that hasn't yet been mentioned, and that is the use of the ternary operator. I know that not all languages support it, but it's actually a good idea to use it in place of a standad if/else due to optimisation.

For those who don't know this operator by name i'm talking about ( ? : )... ie. ( condition ? do if true : do if false ).

When building game code we're obviously worried about the performance that we can gain from any area of our code, and this one of them (depending on how smart the compiler is Smiley ).  If you have a good compiler (which most serious game developers do) then using this:
Code:
y = x == 0 ? z : y;
instead of this
Code:
if( x == 0 ) y = z;
Will allow the (good) compiler to avoid branching - which avoids the cost that goes with it.

If you're interested in more info like this, have a read of the Writing Efficient Game Code for
Next-Gen Console Architectures
article on Gamasutra. It's not a complete reference, but there's some interesting stuff in there.

All the best Smiley
TC.


In order to understand recursion, one must first understand recursion.
Offline  
Read January 02, 2006, 02:37:20 PM #11
Olofson

Re: Case Statement VS If Statement

When building game code we're obviously worried about the performance that we can gain from any area of our code, and this one of them (depending on how smart the compiler is Smiley ).  If you have a good compiler (which most serious game developers do) then using this:
Code:
y = x == 0 ? z : y;
instead of this
Code:
if( x == 0 ) y = z;
Will allow the (good) compiler to avoid branching - which avoids the cost that goes with it.

In my experience, a good compiler will generally generate code based on the logical meaning of the source code, ignoring whatever syntax quirks you use. However...

...in this case, there is a difference, at least with GNU gcc 3.4.4 on Linux/AMD64. The ternary version uses cmove, while the if version uses a branch. This is regardless of optimization level, except -O0, where both versions generate branches.

Either way, these days, branches are a tricky business...! Branches are extremely fast as long as they can be correctly predicted. I hacked a simple test, but the results are vague. Depending on optimization level (which affects only the outer test loop...) and branch/no branch pattern, there are slight differences; sometimes the ternary version is faster, and sometimes the conditional version is faster. I'll post the code if anyone would like to play with it.


//David
Offline  
Read January 02, 2006, 09:27:16 PM #12
oNyx

Re: Case Statement VS If Statement

Premature optimisation is the root of all evil.

I use ?: in 4k alot, because it saves some bytes (java). Other than that I rarely use it.

Well, just use a profiler and care about those spots, which actually need extra work. Spending some hours with optimisations which may or may not yield 1 frame more is a waste of time. You'll gain way more performance if you take care about the critical spots.
Offline  
Read January 02, 2006, 11:59:56 PM #13
Olofson

Re: Case Statement VS If Statement

Premature optimisation is the root of all evil.

Very true indeed.

Also, low level optimization of this kind is just a final touch. The real speedups come from high level optimizations. Figuring out a better algorithm is usually a lot more worthwhile than trying to optimize the code of an inefficient algorithm.


//David
Offline  
Read January 03, 2006, 01:47:20 AM #14
oNyx

Re: Case Statement VS If Statement

Also very true indeed. Smiley
Offline  
Read January 03, 2006, 03:41:48 AM #15
caseyd

Re: Case Statement VS If Statement

I wouldn't worry about all that much. If your if..else or case code blocks are getting that big, than I would highly recommend researching state machines or possibly looking at a new design for what your trying to accomplish.
Offline  
Read January 03, 2006, 11:52:16 AM #16
Matt McFarland

Re: Case Statement VS If Statement

I'm using case select on simple checks..I find it rather simple certainly if I'm doing things based on one condition!  Thanks Smiley


<a href="http://www.mattmcfarland.com/flash/myFlashSig.swf" target="_blank">http://www.mattmcfarland.com/flash/myFlashSig.swf</a>
Offline  
Read January 11, 2006, 12:12:03 PM #17
TheColonial

Re: Case Statement VS If Statement

Premature optimisation is the root of all evil.
Also, low level optimization of this kind is just a final touch.

How is it the root of all evil? Using a ternary in this case can hardly be considered as the spawn of satan. What is wrong with doing that if you know you can possibly benefit from it?

And I can't really see how this can be labelled as low level either. Sure the choice of algorithms and highER level structure can do a great deal more for optimisation, but things like this are handy tricks that a day-to-day coder should know - regardless of whether they're in an optimisation phase or not.

TC.


In order to understand recursion, one must first understand recursion.
Offline  
Read January 12, 2006, 12:33:26 AM #18
Olofson

Re: Case Statement VS If Statement

Premature optimisation is the root of all evil.
Also, low level optimization of this kind is just a final touch.

How is it the root of all evil? Using a ternary in this case can hardly be considered as the spawn of satan.

It's not. It's basically just an alternative syntax. In some cases, I find it clearer than the corresponding if solution, and I guess that's why it's there in the first place.

The "premature optimization" line of discussion here is about optimization in general, and not specifically about the ternary.

Quote
What is wrong with doing that if you know you can possibly benefit from it?

Nothing, unless it makes the code hard to read - which goes for "optimization" in general. When faced with a problem with multiple more or less obvious solutions, go for the fastest one that doesn't have obvious side effects. Sometimes, thinking a bit about performance (as in, getting the job done with fewer operations) results in code that is both faster and simpler.

When you start using LUTs and various obscure algorithms, sometimes without even knowing for sure whether they'd actually be faster in real life, or if the code will run often enough that performance actually matters - that's when you're on the wrong track. (And as this hardly applies to the ternary, I have to conclude that most of this discussion is off topic.)


//David
Offline  
Read January 12, 2006, 12:48:22 AM #19
2dguy

Re: Case Statement VS If Statement

"Also, low level optimization of this kind is just a final touch. The real speedups come from high level optimizations..."

I think the only REAL places we can make a dent in frame rate is the rendering loop. How we sort out textures, batch things, etc,etc, really makes the most difference. I doubt most shoot-em-up ai or collision checking optimizations are going to increase your frame rate that much. Try taking out your render loop and see how fast your code is running. Wink
Offline  
Read January 12, 2006, 05:07:35 AM #20
oNyx

Re: Case Statement VS If Statement

Depending on the type of shoot em up you can spend quite a lot of time with collision detection. Trying different things there can make a big difference.

"Premature optimisation is the root of all evil."

Thats just some famous quote, every programmer should know. Low level optimisations make the code uglier and at the end of they day they often arent worth the trouble, because you wasted precious time with parts which arent run often enough or because the optimisation wasnt faster or in fact even slower... like you move some variable creation out of the loop, because you think its too expensive... and then the scoping is different, which makes it slower at the end. If you cant compare, you cant know if its actually faster.

The best approach is to make it run first. The code should be as clean and simple as possible. Then make it run correct (heh). And then its time to optimise. Identify the real bottlenecks with a profiler (then you have some real numbers) and care about those.

The advantages of this approach are lots of saved time and very clean *and* faster code (because you have more time for dealing with the real bottlenecks).

Tenary by itself isnt bad. I like to use it for side effect free "inline branching"... like depending on some variable I want to show either this or that message. Then tenary is a nice and clean solution.
Offline  
Read January 13, 2006, 05:05:46 AM #21
solidcube

Re: Case Statement VS If Statement

Inlining and unrolling are both very important... if you want to see what the compiler is doing, get it to pump out the intermediate stage and examine the assembly code.  It may not be inlining something you want inlined, and even smart ones sometimes don't unroll loops on their own like they should... looking at the assembly is the best way to figure this out.
Offline  
Read January 13, 2006, 06:25:32 AM #22
d000hg

Re: Case Statement VS If Statement

I can't comment on how different languages/compilers treat case Vs if/else, but writing your logic to get any kind of speed boost from this is ridiculous; any difference in speed is going to be tiny.
You want your logic code to be readable and extendable; for multiple options I reckon switch/cases win here. Especially when you want to group multiple cases to the same action ie
Code:
case 1:
case 2:
case 3:
 do stuff;
 break;
The corresponding if statement would be ugly.
Offline  
Pages: [1]   Go Up
Jump to:  

Page created in 0.1 seconds with 17 queries.