Java-Gaming.org
Play Revenge of the Titans! The situation is critical. We need fancy commanders to defend Earth, the moon, Mars!
Featured games (78)
games approved by the League of Dukes
Games in Showcase (404)
games submitted by our members
Games in WIP (289)
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 1952 times)
0 Members and 1 Guest are viewing this topic.
Offline Vladiedoo

Senior Member


Medals: 11



« Posted 2012-04-08 00: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: 264
Projects: 2


I'm the King!


« Reply #1 - Posted 2012-04-08 01: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

JGO Coder


Medals: 7
Projects: 1


Indie Games FTW!


« Reply #2 - Posted 2012-04-08 04: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 04:51:07 »

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

Offline ra4king

JGO Kernel


Medals: 264
Projects: 2


I'm the King!


« Reply #4 - Posted 2012-04-08 07: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

Senior Member


Medals: 11



« Reply #5 - Posted 2012-04-08 20:53:33 »

Wow this was really thorough information, thanks for the feedback everyone.
Offline princec
« League of Dukes »

JGO Kernel


Medals: 194
Projects: 3


Eh? Who? What? ... Me?


« Reply #6 - Posted 2012-04-09 00: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
« Reply #7 - Posted 2012-04-09 01: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 Coder


Medals: 2


falling into the abyss of reality


« Reply #8 - Posted 2012-04-09 03: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!
Offline ra4king

JGO Kernel


Medals: 264
Projects: 2


I'm the King!


« Reply #9 - Posted 2012-04-09 03: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!
Play the free demo of Revenge of the Titans!
Offline Riven
« League of Dukes »

JGO Overlord


Medals: 437
Projects: 4


Hand over your head.


« Reply #10 - Posted 2012-04-09 03: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
Projects: Revenge of the Titans, Titan Attacks, Droid Assault, and Ultratron
Offline ra4king

JGO Kernel


Medals: 264
Projects: 2


I'm the King!


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

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

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

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

Offline Riven
« League of Dukes »

JGO Overlord


Medals: 437
Projects: 4


Hand over your head.


« Reply #13 - Posted 2012-04-09 04: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
Projects: Revenge of the Titans, Titan Attacks, Droid Assault, and Ultratron
Offline sproingie
« Reply #14 - Posted 2012-04-09 05: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

JGO Knight


Medals: 36



« Reply #15 - Posted 2012-04-09 22: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.

Play Revenge of the Titans! The situation is critical. We need fancy commanders to defend Earth, the moon, Mars!
 
Play Revenge of the Titans! The situation is critical. We need fancy commanders to defend Earth, the moon, Mars and Titan!

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

The first screenshot will be displayed as a thumbnail.

The invasion has landed! On Mars! And you're there to beat 'em!
cubemaster21 (34 views)
2013-05-17 21:29:12

alaslipknot (42 views)
2013-05-16 21:24:48

gouessej (72 views)
2013-05-16 00:53:38

gouessej (71 views)
2013-05-16 00:17:58

theagentd (79 views)
2013-05-15 15:01:13

theagentd (74 views)
2013-05-15 15:00:54

StreetDoggy (116 views)
2013-05-14 15:56:26

kutucuk (139 views)
2013-05-12 17:10:36

kutucuk (140 views)
2013-05-12 15:36:09

UnluckyDevil (147 views)
2013-05-12 05:09:57
Complex number cookbook
by Roquen
2013-04-24 12:47:31

2D Dynamic Lighting
by Oskuro
2013-04-17 16:46:12

2D Dynamic Lighting
by Oskuro
2013-04-17 16:45:57

2D Dynamic Lighting
by Oskuro
2013-04-17 16:23:20

Noise (bandpassed white)
by Roquen
2013-04-05 17:36:01

Noise (bandpassed white)
by Roquen
2013-04-03 16:17:38

Java Data structures
by Roquen
2013-03-29 13:21:12

Topic Request
by kutucuk
2013-03-22 21:42:01
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!
Page created in 0.165 seconds with 21 queries.