Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Page 1 of 2 12 LastLast
Results 1 to 15 of 26
  1. #1
    Senior Coder xelawho's Avatar
    Join Date
    Nov 2010
    Posts
    2,984
    Thanks
    56
    Thanked 557 Times in 554 Posts

    switch vs. if else

    just a general question really... now that I've finally started using switches, it seems to me that they're just a big if /else if statement, with an else thrown in at the end for the default.

    but that can't be right. I know that in javascript there are a million ways to achieve the same result, but why would they (whoever they are) go to the trouble of making two basic operations that do exactly the same thing?

    to me it seems that switches are better for lots of conditions and if else is a quick way to work with two or three, but apart from readability, are there any inherent advantages in choosing one approach over the other?

    all opinions appreciated, and I hope I don't start another argument.

  • #2
    Senior Coder
    Join Date
    Dec 2010
    Posts
    2,398
    Thanks
    12
    Thanked 570 Times in 563 Posts
    Switch and if/else if are not doing exactly the same thing. If/else if is much more flexible and switch is much easier to use if the compared expression is the same

    Example of if/else if that cannot (easily) be converted into switch
    Code:
    if(a==5) {
       ...
    } else if (b==7) {
       ...
    }

  • #3
    Rockstar Coder
    Join Date
    Jun 2002
    Location
    USA
    Posts
    9,074
    Thanks
    1
    Thanked 328 Times in 324 Posts
    A switch statement can be much faster in some cases because it will be turned into a jump table. So instead of having to evaluate a number of conditions until one is true, the matching condition can be jumped to immediately.
    OracleGuy

  • #4
    Senior Coder rnd me's Avatar
    Join Date
    Jun 2007
    Location
    Urbana
    Posts
    4,401
    Thanks
    11
    Thanked 595 Times in 575 Posts
    Quote Originally Posted by devnull69 View Post
    Example of if/else if that cannot (easily) be converted into switch
    Code:
    if(a==5) {
       ...
    } else if (b==7) {
       ...
    }
    BS!
    since case operators accept an expression (though folks typically just a static primitive), just overload the switch:
    Code:
    switch(true) {
      case a==5: break;
      case b==7: break;
      default: break;
    }
    now you can do several comparisons mid-switch... pretty cool huh? keep it on the downlow.


    personally, for one-switch-one expressions, i prefer look up tables, which are MUCH faster for those simple one determine another things:


    Code:
    var myLetter="c";
    var myPhonic={
      a: "aye",
      b: "bee",
      c: "see"
    }[myLetter];
    
    //myPhonic=="see"...
    Last edited by rnd me; 08-30-2011 at 10:33 PM.
    my site (updated 13/9/26)
    BROWSER STATS [% share] (2014/9/03) IE7:0.1, IE8:4.6, IE11:9.1, IE9:3.1, IE10:3.0, FF:17.2, CH:46, SF:11.4, NON-MOUSE:38%

  • #5
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    26,588
    Thanks
    80
    Thanked 4,497 Times in 4,461 Posts
    Simple answer: switch can only be used to test a single value and thus a single condition.
    It is much much more efficient than if...else if...else if... but it's also much more limited.

    Use it if it works for the situation. Don't if it doesn't.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #6
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    26,588
    Thanks
    80
    Thanked 4,497 Times in 4,461 Posts
    And I admit (shamelessly) to having used RndMe's trick. But I think it's a bad coding style simply because it makes it much less clear what you are trying to accomplish. Pity the poor neophyte who is assigned to maintaining your code 3 years after you have left the company. He would want to shoot you.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #7
    Senior Coder rnd me's Avatar
    Join Date
    Jun 2007
    Location
    Urbana
    Posts
    4,401
    Thanks
    11
    Thanked 595 Times in 575 Posts
    Quote Originally Posted by oracleguy View Post
    A switch statement can be much faster in some cases because it will be turned into a jump table. So instead of having to evaluate a number of conditions until one is true, the matching condition can be jumped to immediately.
    that would violate the spec. each case is evaluated until a true expression is found, and which point all subsequent cases are executed until a break is encountered.

    example:

    Code:
    var x=2;
    var out="blank";
    
    switch(x){
      case 1: out="one"; 
      case 2: out="two"; 
      case 3: out="three"; break;
      default: out="defaulted"; 
    }
    
    alert(out); //shows: "three" (!@#$*)
    which reminds me, watch those breaks everyone!
    my site (updated 13/9/26)
    BROWSER STATS [% share] (2014/9/03) IE7:0.1, IE8:4.6, IE11:9.1, IE9:3.1, IE10:3.0, FF:17.2, CH:46, SF:11.4, NON-MOUSE:38%

  • #8
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    26,588
    Thanks
    80
    Thanked 4,497 Times in 4,461 Posts
    Yeah, JS's version of switch is uglier than C/C++/Java. In those languages, the case *must* be a constant value, not an expression. The result is that, indeed, the compiler can build a jump table that can be enormously efficient.

    Unless a JS compiler is smart enough to realize that all the case values are constants and then do the same (build a jump table), it has no real choice but to evaluate the case expressions at run time, so a lot of performance advantage over if..else is lost. But who knows: Maybe modern JS compilers *are* that good.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #9
    Rockstar Coder
    Join Date
    Jun 2002
    Location
    USA
    Posts
    9,074
    Thanks
    1
    Thanked 328 Times in 324 Posts
    Quote Originally Posted by rnd me View Post
    that would violate the spec. each case is evaluated until a true expression is found, and which point all subsequent cases are executed until a break is encountered.
    Well in the case of languages that don't allow you to do have evaluations on each case statement, a switch is incredibly more efficient (when checking against a constant value). I didn't know JS let you do that. It seems like a strange feature to support. Hopefully the JS compiler uses a jump table when the switch is only evaluating a constant value so if you use a switch traditionally (dare I say correctly), you get the speed improvement.
    OracleGuy

  • #10
    Senior Coder xelawho's Avatar
    Join Date
    Nov 2010
    Posts
    2,984
    Thanks
    56
    Thanked 557 Times in 554 Posts
    interesting. actually more interesting than I'd anticipated, so thank you all.

    A couple of clarifications (and I am googling this, too, but it's obviously nice to see a dynamic discussion rather than isolated opinions)...

    Old Pedant, I'm assuming that when you talk about rnd me's 'trick' you're talking about this one:
    Code:
    switch(true) {
      case a==5: break;
      case b==7: break;
      default: break;
    }
    but it seems to me to be as readable/comprehensible as any of the other methods... can you maybe give a more "real-lifeish" example of how using this approach will result in code that would be hard to understand/modify by someone else in the future?

    and, thinking about it more, isn't

    Code:
    if(a==5) {
       ...
    } else if (b==7) {
       ...
    }
    really two separate if statements, ie it would be exactly the same to use

    Code:
    if(a==5) {
       ...
    } if (b==7) {
       ...
    }
    meaning that really it could, for some reason, be done as

    Code:
    switch(a) {
    case 5: ...;
    break; // although I guess with only one condition to check the break is not strictly necessary here?
    } 
    switch(b) {
    case 7: ...;
    break; // ditto
    }
    the other one was minor - I see we're talking about jump tables and look up tables (which I hadn't heard of before, but seem to be interesting, too)... are these the same thing, just with different names and if so, is that the method described as "Lookup by object" here and (sorry, but my curiosity has been piqued) being that the "Lookup by array" method comes out more or less the same in terms of speed, are there any substantive differences between those two approaches?

    thanks again for your thoughts.
    Last edited by xelawho; 08-31-2011 at 02:56 PM. Reason: thinking about it more

  • #11
    Senior Coder rnd me's Avatar
    Join Date
    Jun 2007
    Location
    Urbana
    Posts
    4,401
    Thanks
    11
    Thanked 595 Times in 575 Posts
    Quote Originally Posted by xelawho View Post
    the other one was minor - I see we're talking about jump tables and look up tables (which I hadn't heard of before, but seem to be interesting, too)... are these the same thing, just with different names and if so, is that the method described as "Lookup by object" here and (sorry, but my curiosity has been piqued) being that the "Lookup by array" method comes out more or less the same in terms of speed, are there any substantive differences between those two approaches?

    thanks again for your thoughts.
    jump table is likely a term for an internally optimization done during compilation time. look up table is the same as "lookup by object" in your link'd page. what they call "Lookup by array" is actually just mis-using the array as an object, so yeah, they are comparable. if you used the array properly (with numerical keys), you would have to loop through all the elements in an iteration procedure like for or indexOf (js1.6/es5).


    if you only need to determine one thing based on a list of possible other things, the look-up table pattern (y={a:1,b:2}[x]) is going to be the fastest, especially when comparing more than a dozen choices.
    my site (updated 13/9/26)
    BROWSER STATS [% share] (2014/9/03) IE7:0.1, IE8:4.6, IE11:9.1, IE9:3.1, IE10:3.0, FF:17.2, CH:46, SF:11.4, NON-MOUSE:38%

  • #12
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    26,588
    Thanks
    80
    Thanked 4,497 Times in 4,461 Posts
    What rndme said. In spaces.

    Additionally:

    *NO*. Doing
    Code:
    if(a==5) {
       ...block1...
    } if (b==7) {
       ...block2...
    }
    is *IN NO WAY* equivalent to doing
    Code:
    if(a==5) {
       ...block1...
    } else if (b==7) {
       ...block2...
    }
    Let's say that indeed a *IS* equal to 5 and b *IS* equal to 7.

    In the first code, *BOTH* if conditions are true and *BOTH* blocks of code WILL be executed.

    With the else in place, block2 will NEVER be executed if block1 is executed.

    And the same is true with your dual switch code.
    Code:
    switch(a) {
    case 5: ...block1...;
    break; 
    } 
    switch(b) {
    case 7: ...block2...;
    break; 
    }
    If a is 5 and b is 7, *BOTH* blocks will be executed.

    With
    Code:
    switch(true) {
      case a==5: ...block1...; break;
      case b==7: ...block2...; break;
      default: ...block3...; break;
    }
    only *ONE* of the blocks will be executed.

    DO NOT TAKE SHORTCUTS if you don't understand the consequences!
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #13
    Senior Coder rnd me's Avatar
    Join Date
    Jun 2007
    Location
    Urbana
    Posts
    4,401
    Thanks
    11
    Thanked 595 Times in 575 Posts
    personally, i almost never use "else if" for readability reasons. once i get a nest or two deep, i find else and a bunch of "}}}"s to be confusing.

    for me, and maybe i'm just dumb (a possibility for sure), i would code it the dummy-proof way:

    Code:
    if(a==5) {
       ...
    } else {
        if (b==7) {... }
    }
    but again, that's just me.

    there's a ton of way to code this sequence, use whatever feels right for you.

    another fool-proof way:
    Code:
    if(a==7){ ... }
    if(a!=7 && b==7){ ... }
    my site (updated 13/9/26)
    BROWSER STATS [% share] (2014/9/03) IE7:0.1, IE8:4.6, IE11:9.1, IE9:3.1, IE10:3.0, FF:17.2, CH:46, SF:11.4, NON-MOUSE:38%

  • #14
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    26,588
    Thanks
    80
    Thanked 4,497 Times in 4,461 Posts
    Ummm...RndMe, you do *NOT* need or get a bunch of "}}}"s if you use if...else correctly.

    Code:
    if ( a == 5 )
    {
         foo = "bananas";
         bar = "apples";
    } else if( b == 7 ) {
        foo = "godzilla";
        zam = "magilla";
    } else if ( c == 971281 ) {
        bar = "howzit";
        zam = "hangin";
    }
    And so on.

    Coded like that, you will never have more than one pair of {...} at a time to worry about.

    Your supposed dummy-proof way is the one that gets you into trouble with counting }'s.
    Code:
    if(a==5) {
       ...
    } else {
        if (b==7) {
            ... 
       } else {
            if ( c == 9 ) {
                ...
           } else {
               if ( d > 7 ) {
                   ...
               }
           }
        }
    }
    Ugh, to say the least.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #15
    Senior Coder rnd me's Avatar
    Join Date
    Jun 2007
    Location
    Urbana
    Posts
    4,401
    Thanks
    11
    Thanked 595 Times in 575 Posts
    yeah, i guess that is cleaner...

    maybe it's just my coding style, but i rarely use ifs, and never use else if.
    i think since i do so much functional, i use return instead of else/else if.

    to some purists, a function should have only one return, but i find it works like a charm on filters and even maps. i guess .map replaces for, and return replaces else.
    i would do it the simple way, but i gotta have my private iteration scope...


    thanks for writing up a coherent example of else if, i might add that to my toolkit. having never had a formal CS education, i've had to feel my way around in the dark on some of these very basic concepts. while i've done alright for myself, it does lead to some "duh" moments every now and then. this is one of them. thanks again.
    my site (updated 13/9/26)
    BROWSER STATS [% share] (2014/9/03) IE7:0.1, IE8:4.6, IE11:9.1, IE9:3.1, IE10:3.0, FF:17.2, CH:46, SF:11.4, NON-MOUSE:38%


  •  
    Page 1 of 2 12 LastLast

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •