Java-Gaming.org Hi !
Featured games (83)
games approved by the League of Dukes
Games in Showcase (525)
Games in Android Showcase (127)
games submitted by our members
Games in WIP (594)
games currently in development
News: Read the Java Gaming Resources, or peek at the official Java tutorials
 
    Home     Help   Search   Login   Register   
Pages: [1]
  ignore  |  Print  
  Switch Statement Versus If Statements  (Read 3836 times)
0 Members and 1 Guest are viewing this topic.
Offline Vladiedoo
« Posted 2012-04-07 22:57:36 »

Hi I'm a huge noob with programming and have a simple question.

Is there a performance or maybe coding time advantage using a Switch statement versus lots of If statements? Or is it just personal preference?

-Thanks!!!
Offline ra4king

JGO Kernel


Medals: 355
Projects: 3
Exp: 5 years


I'm the King!


« Reply #1 - Posted 2012-04-07 23:38:43 »

Switch statements are cleaner if you would have many many if statements otherwise. They are also useful if you want multiple values to run the same code.

Instead of:
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
int value = derp();

if(value == 2 || value == 5) {
    doThis();
}
else if(value == 3 || value == 7) {
    doThat();
}
else if(value == 1 || value == 0) {
    doThose();
}
else if(value < 0 || value >= 8 || value == 6 || value == 4) {
    DoThese();
}


This would simply go down to:
1  
2  
3  
4  
5  
6  
switch(derp()) {
    case 0: case 1:          doThose(); break;
    case 2: case 5:          doThis(); break;
    case 3: case 7:          doThat(); break;
    case 4: case 6: default: doThese(); break;
}



EDIT: @Riven, the "default" keyword doesn't highlight :S

Offline _Al3x

Senior Devvie


Medals: 7


Indie Games FTW!


« Reply #2 - Posted 2012-04-08 02:08:15 »

I like If's when you need to meet previous conditions and would like to handle what happens in the middle:

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
public void test(boolean a,boolean b,boolean c){
      if (a){
         statement;
         if(b){
            statement;
            if(c){
               statement;
            }else{
               statement;
            }
         }else{
            statement;
         }
      }else{
         statement;
      }
   }


Also, in really complicated algorithms you could use both:

1  
2  
3  
4  
5  
6  
7  
public void test(int a,boolean b,boolean c){
      switch(a) {
       case 0: if(b && c){ statements } else { statements } break;
       case 1: if(b && !c){ statements } else { statements } break;
       case 2: if(!b && !c){ statements } else { statements } break;
      }
   }


As far as I know, there are no performance gain or loss between either each of them, just use the one that fits best your situation and makes your code clearer.

BTW, off topic, I really hate the "break" command, so I try not to use switch Sad it has something to do with "go-to" in my head, so I hate it  Angry

tl;dr
Both are just fine, they are tools to control the flow of the program, just use the one that fits you best Smiley

Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline ReBirth
« Reply #3 - Posted 2012-04-08 02:51:07 »

IMO If is more general than Switch in term of use. If can take more conditional syntax.

Offline ra4king

JGO Kernel


Medals: 355
Projects: 3
Exp: 5 years


I'm the King!


« Reply #4 - Posted 2012-04-08 05:02:10 »

BTW, off topic, I really hate the "break" command, so I try not to use switch Sad it has something to do with "go-to" in my head, so I hate it  Angry=
There is absolutely no reason to hate the 'break' command, mostly because you can't live without, also because it is nothing like goto.

Offline Vladiedoo
« Reply #5 - Posted 2012-04-08 18:53:33 »

Wow this was really thorough information, thanks for the feedback everyone.
Offline princec

« JGO Spiffy Duke »


Medals: 422
Projects: 3
Exp: 16 years


Eh? Who? What? ... Me?


« Reply #6 - Posted 2012-04-08 22:30:10 »

switch uses optimised code to select values and jump to the appropriate code. A switch on a reasonable number of values will be somewhat faster than the equivalent code formed from if-elseifs.

Cas Smiley

Offline sproingie

JGO Kernel


Medals: 202



« Reply #7 - Posted 2012-04-08 23:49:27 »

Switch/case is great with enums.  For strings (1.7 and up) it switches on the string's hashCode, which should be a great deal faster than testing them in series.  The important part is not which is faster, it's which is appropriate.


Offline Abuse

JGO Knight


Medals: 14


falling into the abyss of reality


« Reply #8 - Posted 2012-04-09 01:05:51 »

For strings (1.7 and up) it switches on the string's hashCode, which should be a great deal faster than testing them in series.  The important part is not which is faster, it's which is appropriate.

I'm torn as to whether that's a 'good thing' (tm).

I'm sure there are a few useful situations where it's perfectly reasonable to switch on Strings, and doing so will no doubt avoid some boiler plate.

However I've a feeling it'll be misused to create bad, or poorly structured code. Using Strings where enums would be a better fit for instance.

Make Elite IV:Dangerous happen! Pledge your backing at KICKSTARTER here! https://dl.dropbox.com/u/54785909/EliteIVsmaller.png
Offline ra4king

JGO Kernel


Medals: 355
Projects: 3
Exp: 5 years


I'm the King!


« Reply #9 - Posted 2012-04-09 01:21:30 »

For strings (1.7 and up) it switches on the string's hashCode, which should be a great deal faster than testing them in series.  The important part is not which is faster, it's which is appropriate.

I'm torn as to whether that's a 'good thing' (tm).

I'm sure there are a few useful situations where it's perfectly reasonable to switch on Strings, and doing so will no doubt avoid some boiler plate.

However I've a feeling it'll be misused to create bad, or poorly structured code. Using Strings where enums would be a better fit for instance.
User input.

Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline Riven
« League of Dukes »

« JGO Overlord »


Medals: 833
Projects: 4
Exp: 16 years


Hand over your head.


« Reply #10 - Posted 2012-04-09 01:23:06 »

User input.
How does that change anything?

Hi, appreciate more people! Σ ♥ = ¾
Learn how to award medals... and work your way up the social rankings
Offline ra4king

JGO Kernel


Medals: 355
Projects: 3
Exp: 5 years


I'm the King!


« Reply #11 - Posted 2012-04-09 01:33:25 »

I'm giving a scenario where strings in switch is helpful.

Offline ReBirth
« Reply #12 - Posted 2012-04-09 02:13:36 »

I use 1.7 and never ever use that string switch until now.

Offline Riven
« League of Dukes »

« JGO Overlord »


Medals: 833
Projects: 4
Exp: 16 years


Hand over your head.


« Reply #13 - Posted 2012-04-09 02:32:44 »

I'm giving a scenario where strings in switch is helpful.
You're still hardcoding string literals in your code, so Enums are still prefered, due to type safety (unlikely you're doing to write those strings only once).

Hi, appreciate more people! Σ ♥ = ¾
Learn how to award medals... and work your way up the social rankings
Offline sproingie

JGO Kernel


Medals: 202



« Reply #14 - Posted 2012-04-09 03:18:06 »

I'm not big on the idea of string switches either, and I never use them, but since strings are hashable and immutable, I don't see much reason to not support them in switches.  It can come in handy for simple command line parsing, for example, since constructing a hashtable is a lot of boilerplate.  It's certainly not the most impressive feature of 1.7 though.

Except on enums, where you actually get warned about unhandled cases, switch in general can tend to lead to sloppy code.  Still useful sometimes.
Offline Danny02
« Reply #15 - Posted 2012-04-09 20:07:20 »

yeah one of my use cases of string switches are when I do file parsing
Pages: [1]
  ignore  |  Print  
 
 
You cannot reply to this message, because it is very, very old.

 

Add your game by posting it in the WIP section,
or publish it in Showcase.

The first screenshot will be displayed as a thumbnail.

toopeicgaming1999 (68 views)
2014-11-26 15:22:04

toopeicgaming1999 (58 views)
2014-11-26 15:20:36

toopeicgaming1999 (13 views)
2014-11-26 15:20:08

SHC (26 views)
2014-11-25 12:00:59

SHC (24 views)
2014-11-25 11:53:45

Norakomi (30 views)
2014-11-25 11:26:43

Gibbo3771 (24 views)
2014-11-24 19:59:16

trollwarrior1 (37 views)
2014-11-22 12:13:56

xFryIx (76 views)
2014-11-13 12:34:49

digdugdiggy (54 views)
2014-11-12 21:11:50
Understanding relations between setOrigin, setScale and setPosition in libGdx
by mbabuskov
2014-10-09 22:35:00

Definite guide to supporting multiple device resolutions on Android (2014)
by mbabuskov
2014-10-02 22:36:02

List of Learning Resources
by Longor1996
2014-08-16 10:40:00

List of Learning Resources
by SilverTiger
2014-08-05 19:33:27

Resources for WIP games
by CogWheelz
2014-08-01 16:20:17

Resources for WIP games
by CogWheelz
2014-08-01 16:19:50

List of Learning Resources
by SilverTiger
2014-07-31 16:29:50

List of Learning Resources
by SilverTiger
2014-07-31 16:26:06
java-gaming.org is not responsible for the content posted by its members, including references to external websites, and other references that may or may not have a relation with our primarily gaming and game production oriented community. inquiries and complaints can be sent via email to the info‑account of the company managing the website of java‑gaming.org
Powered by MySQL Powered by PHP Powered by SMF 1.1.18 | SMF © 2013, Simple Machines | Managed by Enhanced Four Valid XHTML 1.0! Valid CSS!