If statements vs case

Hershel Fisch hershf at rgllc.us
Mon Feb 26 13:11:20 EST 2007


On 2/26/07 12:35 PM, "Richard Gaskin" <ambassador at fourthworld.com> wrote:
Hi,
Is the below the original code, if yes I'd make some comments if possible.

> Mark Smith wrote:
>> I just ran a very simple benchmark test, which suggests that if/then
>> goes about 20% faster than switch/case.
> 
> I get different results here, but I had to rewrite the if-then test as
> the example posted as it wasn't executing the same logic as the switch
> block.  In the "if" example the "c" case didn't fall through to also
> execute the "d" case as it did in the "switch" example, and the "e" case
> wasn't handled at all.
> 
> So I wrote a fresh pair of examples that test all possible cases,
> running each full set 10000 iterations. They each produce the same
> logical result at this point, with these times on my MacBook Pro:
> 
> if:89ms switch:74ms
> if result:140000 switch result:140000
> 
> The timings aren't surprising given the extra evaluations needed to get
> the same effect using "if" as with the "switch" fall-through behavior.
> 
> Please double-check the benchmark handler below to make sure that both
> tests are using equivalent logic, and look for ways the "if-then" might
> be better optimized:
> 
> 
> 
> local sResult
> 
> on mouseUp
>  -- number of test iterations:
>  put 10000 into n
>  -- load var with all possible values:
>  put "abcde" into s
>  --
>  --
>  -- TEST 1: if-then
>  put 0 into sResult
>  put the millisecs into t
>  repeat n
>    --
>    repeat for each char tVar in s
>    If tVar ="a" or tVar ="b" then
>        DoThing1
>      else                              -------if tVar = "c" or tVar = "d" then
this one is out of the order how about with out this line because its not in
sequences and the same thing below its not comparable to the case statement.
>        if tVar = "c" then
>          DoThing2
>        end if
>        DoThing3
>      Else If tVar ="e" then
>        DoThing4
>      End if
>    end repeat
>    --
>  end repeat
>  put the millisecs - t into t1
>  put sResult into tResult1
>  --
>  -- TEST 2: switch
>  put 0 into sResult
>  put the millisecs into t
>  repeat n
>    --
>    repeat for each char tVar in s
>      switch tVar
>      case "a"
>      case "b"
>        DoThing1
>        break
>      case "c"
>        DoThing2
>      case "d"
>        DoThing3
>        break
>      case "e"
>        DoThing4
>      end switch
>    end repeat
>    --
>  end repeat
>  put the millisecs - t into t2
>  put sResult into tResult2
>  --
>  -- show results:
>  put "if:"&t1 &"ms"&&"switch:"& t2&"ms"&cr&\
> "if result:"& tResult1 &&"switch result:"&tResult2
> end mouseUp
> 
> 
> 
> on DoThing1
>  add 1 to sResult
> end DoThing1
> 
> on DoThing2
>  add 2 to sResult
> end DoThing2
> 
> on Dothing3
>  add 3 to sResult
> end Dothing3
> 
> on DoThing4
>  add 4 to sResult
> end DoThing4
> 
> 
> 




More information about the use-livecode mailing list