Page 1 of 2 12 LastLast
Results 1 to 15 of 18

Thread: Case v. If/Then

  1. #1
    kelliel
    Guest

    Case v. If/Then

    I remember reading which is faster, but at this point, I can't remember.

    So, which is faster

    Select Case?

    or

    If/Then

    Thanks

  2. #2
    Platinum Lounger
    Join Date
    Feb 2001
    Location
    Yilgarn region of Toronto, Ontario
    Posts
    5,453
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Re: Case v. If/Then

    Faster for who.what?

    I'm against speed unless the code is first readable by humans (and I don't write particularly readable code, I admit).

    Kevin went on quite abit about timing fucntions. part of the thread is here at
    <A target="_blank" HREF=http://www.wopr.com/cgi-bin/w3t/showthreaded.pl?Cat=&Board=vb&Number=19515&page=&v iew=&sb=&vc=1#Post19515>Timer Function</A>

  3. #3
    kelliel
    Guest

    Re: Case v. If/Then

    Didn't say I would change the code I'm writing. I was just trying to remember.

    I have read some of your thoughts on the problem, and I agree. With computers now running at 1.5 GHz, "speed" has become a nonissue.

    Currently, I am working on some code where I have a pair of nested Select Case. Personally, I like Select Case. It is easier to read.

    But I was just wondering which ran faster.

  4. #4
    Xiao Bin
    Guest

    Re: Case v. If/Then

    If ... elseif ... will tend to be significantly faster.
    For discussion, see:
    <A target="_blank" HREF=http://www.microsoft.com/OfficeDev/Articles/movs101.htm>http://www.microsoft.com/OfficeDev/Articles/movs101.htm</A>

  5. #5
    Platinum Lounger
    Join Date
    Feb 2001
    Location
    Yilgarn region of Toronto, Ontario
    Posts
    5,453
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Re: Case v. If/Then

    >Didn't say I would change the code

    Big question: "Is it working as it now stands?", because if it ain't broke ...


    So you've been here?

    <A target="_blank" HREF=http://www.wopr.com/cgi-bin/w3t/showthreaded.pl?Cat=&Board=vb&Number=25099&page=&v iew=&sb=&vc=1#Post25099>Select case Vs. If </A>



    My vague thoughts are that Select Case vs. If/Elseif (readability) somehow depends on the sorts of values one might expect. My TERRIBLE example was testing 16 consecutive hexadecimal values. Aaaarg.

    There seems to be a difference if the values are all over the place, as in "Adelaide", "Perth", "Melbourne".


    Speed of execution might depend on the anticipated frequency of cases. For example, if 95% of sane people vote "Perth" as the most beautiful capital city in the world, it'd make sense to test for "Perth" before all others, regardless of whether we are using IF/Else or Case.

    This, of course, paves the way for a piece of self-modifying code that changes the sequence of the tested values dynamically according to the trends observed during execution. I'll get on to that just as soon as I've finished my research on search tags



    From a hardware architecture point of view, there was no difference in implementation in the early days. The machine instruction set was so simple that if you COULD write a CASE in a language, it got compiled as a cascade of conditional branches (IF/ElseIF) anyway.


    Nowadays, maybe the 1.7G Intel chip announced (yesterday) has a hard-wrired CASE instruction.


    In 1979 CAP Sogeti was dabbling in a chip whose design was driven by the language requirements.

  6. #6
    Plutonium Lounger
    Join Date
    Dec 2000
    Location
    Sacramento, California, USA
    Posts
    16,775
    Thanks
    0
    Thanked 1 Time in 1 Post

    Re: Case v. If/Then

    Hate to disagree, but every time I've heard Ken Getz speak (more recent than the white paper, by the way), he and every other speaker has claimed that Select Case is faster because it is optimized. In my unscientific experience, Select Case is much faster.
    Charlotte

  7. #7
    Super Moderator jscher2000's Avatar
    Join Date
    Feb 2001
    Location
    Silicon Valley, USA
    Posts
    23,112
    Thanks
    5
    Thanked 93 Times in 89 Posts

    Re: Case v. If/Then

    Could that be the wrong URL? I didn't see that comparison in there. He says do NOT use IIf, Choose, and Select when you can use If...Then...End If or Select Case. I think, in fact, VBA must do the same type of analysis for both If...Then...End If and Select Case: evaluate each test in sequence until one matches, execute, then exit the structure.

    Anyway, Chris has already shared his views on "significant" performance improvements in our exciting thread on By Ref and By Val. Let's not go there. <img src=/S/laugh.gif border=0 alt=laugh width=15 height=15>

  8. #8
    Platinum Lounger
    Join Date
    Dec 2000
    Location
    Queanbeyan, New South Wales, Australia
    Posts
    3,730
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Re: Case v. If/Then

    I'll agree with that.

    And to add to points which have been raised by Chris previously somewhere- about performance gains being miniscule in the whole scheme of things.

    Readability has been mentioned in thwe thread- but can we quantify that?

    What's the human cost in a routine which is fast but impossible to understand? What does that cost the organisation in terms of the cost to change it- for the time for the programmer to uderstand it, and to modify it successfully? And to havce it tested properly?

    How important is it that "if ... then ... elesif ..." it more/less effiecient than "select case ..."? In terems of cost to the organisation, the more readable/understandable will win evey time- except in the most exceptional circumstances. Possible by thousands of dollars.

    So I'm putting my two cents on whatever looks the clearest.
    Subway Belconnen- home of the Signboard to make you smile. Get (almost) daily updates- follow SubwayBelconnen on Twitter.

  9. #9
    Plutonium Lounger
    Join Date
    Dec 2000
    Location
    Sacramento, California, USA
    Posts
    16,775
    Thanks
    0
    Thanked 1 Time in 1 Post

    Re: Case v. If/Then

    Every speaker I've ever heard recommends Select Case as being faster, but it isn't suitable for every situation.

    Select Case is DIFFERENT from If End If. Select case evaluates a single condition and provides different handling for each possible value. It is fast since it does not continue evaluating code after it finds a match, while If End If evaluates every branch regardless. It is easy to read since the possible values and the associated handling is laid out in each Case.

    If End If allows the use of the ElseIf branch, so you can evaluate totally different things in the same construct.
    Charlotte

  10. #10
    Xiao_Bin
    Guest

    Re: Case v. If/Then

    Hi Charlotte, many thanks for disabusing me of that one. A welcome liberation :-)

  11. #11
    Xiao_Bin
    Guest

    Too early to put speed aside, alas ...

    Ghz speeds should, of course, make speed irrelevant, but it hasn't quite happened yet... Given the huge layers of abstraction that programmers keep piling on (COM interface for a VBA example), a small optimization, possibly at the expense of readability, can still make the difference between usable code and something far too slow to actually use.

    An obvious example might be something like the following Word macro, which loops through the characters in the active document:
    <pre>Sub CountVowels()
    Const upper_A As Long = 65
    Const upper_E As Long = 69
    Const upper_I As Long = 73
    Const upper_O As Long = 79
    Const upper_U As Long = 85

    Const lower_a As Long = 97
    Const lower_e As Long = 101
    Const lower_i As Long = 105
    Const lower_o As Long = 111
    Const lower_u As Long = 117

    Dim oChars As Word.Characters
    Dim strChars As String
    Dim lngCharCode As Long
    Dim lngA As Long
    Dim lngE As Long
    Dim lngI As Long
    Dim lngO As Long
    Dim lngU As Long
    Dim i As Long



    '-------------------------------------------------
    'This clear but unoptimised version proves
    'so slow as to be unusable on a term paper, even at 1Ghz

    'Set oChars = ActiveDocument.Range.Characters
    'For i = 1 To oChars.Count
    ' lngCharCode = Asc(oChars(i))
    '-------------------------------------------------

    '-------------------------------------------------
    'This slightly rewritten version is more or less instantaneous
    strChars = ActiveDocument.Range.Text
    For i = 1 To Len(strChars)
    lngCharCode = Asc(Mid$(strChars, i, 1))
    '-------------------------------------------------

    Select Case lngCharCode
    Case upper_E, lower_e
    lngE = lngE + 1
    Case upper_A, lower_a
    lngA = lngA + 1
    Case upper_I, lower_i
    lngI = lngI + 1
    Case upper_O, lower_o
    lngO = lngO + 1
    Case upper_U, lower_u
    lngU = lngU + 1
    End Select
    Next

    Debug.Print "A", "E", "I", "O", "U"
    Debug.Print lngA, lngE, lngI, lngO, lngU
    End Sub
    </pre>


  12. #12
    Platinum Lounger
    Join Date
    Feb 2001
    Location
    Yilgarn region of Toronto, Ontario
    Posts
    5,453
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Re: Case v. If/Then

    > And to add to points which have been raised by Chris previously somewhere- about performance gains being miniscule in the whole scheme of things.



    That was the 11 miliseconds-per-fortnightly run of the BHP payroll system. Or 2 minutes over a whole year, or soemthing. True Story.


    Readability has been mentioned in thwe thread- but can we quantify that?


    Yes. Timesheets provide accurate measures of time taken to solve debugging problems. If you tracked time taken by debugging programmers to solve problems in MY code as against problems taken in YOUR code, there would be a difference. One of us writes more readable code (but I'm better at emails, right? GRIN!)


    How important is it that "if ... then ... elesif ..." it more/less effiecient than "select case ..."? In terems of cost to the organisation, the more


    Radability too can be tested by time - take a team of programmers, flash code on a screen for five seconds, ask them to write down what it does, count how many got it right. Repeat the exercise for different code fragments, authors etc.

    I figure that such a study would soon provide some general guidelines like this:


    Use nested ElseIfs if the number of values being tested is less than 5. Use Select Case if the number is greater than 5.

    After all, a select case is a bit like a shopping list that our eyes can run down, mentally ticking off items as being relevant or not (when reading code in debugging practice)

  13. #13
    Super Moderator jscher2000's Avatar
    Join Date
    Feb 2001
    Location
    Silicon Valley, USA
    Posts
    23,112
    Thanks
    5
    Thanked 93 Times in 89 Posts

    Re: Case v. If/Then

    > Use nested ElseIfs if the number of values being tested is less than 5. Use Select Case if the number is greater than 5.

    I'd say if the test is the same and all you are doing is checking values, Select Case looks better for more than 2 possible values. It also has the benefit of Case Else, which in my projects usually pops up something like MsgBox "The programmer screwed up!"

  14. #14
    Platinum Lounger
    Join Date
    Feb 2001
    Location
    Yilgarn region of Toronto, Ontario
    Posts
    5,453
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Re: Case v. If/Then

    >It also has the benefit of Case Else


    I like this. I usually force myself to include the Else in every If in an attempt to force myself to think about alternatives, to nip the "this can never happen" syndrome in the bud.

  15. #15
    Platinum Lounger
    Join Date
    Feb 2001
    Location
    Yilgarn region of Toronto, Ontario
    Posts
    5,453
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Re: Case v. If/Then

    > (SELECT CASE) is fast since it does not continue evaluating code after it finds a match, while If End If evaluates every branch regardless ...

    I've thought a bit more about this.

    1) A linear SELECT CASE will (always?) evaluate the first CASE, then the second CASE and so on. Execution speed can be optimised by careful selection of the sequence. If 95% of the candidates are the string "DIM", then having CASE "DIM" as the first CASE makes a difference.

    2) I suppose one could have nested SELECT CASE statements, but I'm not going to be the first programmer to try to sell the idea.

    3) Nested If THEN ELSE may at times provide some degree of control over cost of processing where, for example, one is processing a set of lexical atoms in a language, and the presence of some atoms depends on the prior occurrence of a previous atom. The nesting would provide a reduced (and hence faster execution) set of tests at an interior level.



    I hope that makes sense. The argument against nested Selects is readability. We're not used to seeing those. We are more familiar with nested IFs.


    If anyone needs a good example, try writing out the syntax and a logic table for the analysis of identifiers (variables and constants) in Word97VBA. Don't forget the dreaded WithEvents keyword.

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
  •