The Order of WHEN Statements

Discussions about the BBC BASIC language, with particular reference to BB4W and BBCSDL
Post Reply
Posts: 51
Joined: Mon 16 Apr 2018, 06:17

The Order of WHEN Statements

Post by MattC » Mon 27 May 2019, 07:38


This is more for information rather than a question. (Forgive me if this information is recorded elsewhere, but I couldn't find it.)

I did a simple trial on the order of WHEN statements in a CASE...ENDCASE clause.

Code: Select all

      T% = TIME
      FOR I% = 1 TO 10000000
        A% = 1 : REM set this to 10 for a second run
        CASE A% OF
          WHEN 1:
          WHEN 2:
          WHEN 3:
          WHEN 4:
          WHEN 5:
          WHEN 6:
          WHEN 7:
          WHEN 8:
          WHEN 9:
          WHEN 10:
      U% = TIME
      PRINT U%-T%
It does absolutely nothing, but it does show that the order of WHEN statements is important when speed is necessary. This conclusion seems obvious when you understand that, unlike a succession of IF...THEN statements, once a WHEN condition is used, the others are completely ignored.

The results (on my computer) are that when A% is set to 1 it takes 1510ms to run (151ns each loop), and when it's set to 10 it takes 4820ms to run (482ns each loop). Calculation suggests that each WHEN line will take an additional 37ns, approx. This may not seem much to the average programmer, but it may well add up if there are a lot of loops and CASE clauses.

Please feel free to add anything to this, or correct me if I'm wrong.


Posts: 61
Joined: Wed 04 Apr 2018, 06:36

Re: The Order of WHEN Statements

Post by KenDown » Fri 14 Jun 2019, 12:22

The other aspect of the order of WHEN statements is that you need to order them carefully, otherwise the one you want may never actually be reached because some other condition was fulfilled first.

Post Reply