Switch or If

Kay C Lan lan.kc.macmail at gmail.com
Thu Apr 23 21:44:44 EDT 2009


You may wish to look back at these two threads, lots of benchmarking, sorry
I haven't figured out how to create links to old threads :-(

Subject: if statements vs case
Date: 27 feb 07
From: Hershel Fisch

Subject: switch case question
Date: 10/22/06
From: Mark Swindell

Basically what has been said so far is correct, timings are similar BUT Dar
Scott in the 2006 thread determined those cases (sorry for the pun) where
one will be faster than the other. I believe the general conclusion was, if
speed meant everything to you, you'd need to benchmark both.

Secondly, Randall Reetz wrote:

A better word for "switch" could have been "first match" as it presents an
> ordered list of conditional tests at the same level, once a match is found
> the interpretor exits the switch list.
>

Whilst this is the 'normal' behaviour we think of, it is not the only
behaviour. If the 'break' keyword does not follow a 'case' structure, then
the statement flow does NOT exit the switch list. I use this all the time,
its a great feature of switch statements that allow the easy creating and
modification of OR conditions

switch tName
  case "Bob"
  case "Bill"
  case "Ben"
    put "boy" into tGender
  break
  case "Sue"
  case "Sally"
  case "Sarah"
    put "girl" into tGender
  break
  default
     answer "A Name I Don't Know"
end switch

I love switch for the benefits of script manageability. IMO they are very
easy to understand, very easy to figure out where to include extra case
structures if needed - something I always struggled with in large nested
if-then-else structures.

Another thing I like is they are fairly easy to manipulate if you need to
make some minor speed improvements. During development, simply by adding a
counting mechanism you can determine which cases are triggered most often
and therefore move those to the top of the structure.

Lastly, I've become fond of using the default structure as a logic error
catch all, as in the above example.

If it's yes/no, on/off, true/false, 1/0 then I use IF, but too often I
discover it's yes/no/maybe, on/off/sleep, true/false/no comment, 1/0/-1 so I
go with SWITCH.



More information about the use-livecode mailing list