Comparing if, else if and select
Suppose we have a paper with sixteen item. We want to set the maximum number of marks for each of the items. We could just code:
if item = 1 then maxmark = 4;Suppose we have 2000 candidates, or 32,000 items. The above code would have to interpret 32,000 if-statements. How about this:
if item = 2 then maxmark = 6;
if item = 3 then maxmark = 6;
if item = 4 then maxmark = 9;
if item = 5 then maxmark = 4;
if item = 6 then maxmark = 6;
if item = 7 then maxmark = 6;
if item = 8 then maxmark = 9;
if item = 9 then maxmark = 4;
if item = 10 then maxmark = 6;
if item = 11 then maxmark = 6;
if item = 12 then maxmark = 9;
if item = 13 then maxmark = 4;
if item = 14 then maxmark = 6;
if item = 15 then maxmark = 6;
if item = 16 then maxmark = 9;
if item in (1, 5, 9, 13) then maxmark = 4;Apart from being more succinct, by using 'in' and 'else', the code now only needs to interpret 2500 if-statements. We can do even better, by putting the most frequent case first:
else if item in (2, 3, 6, 7, 10, 11, 14, 15) then maxmark = 6;
else maxmark = 9;
if item in (2, 3, 6, 7, 10, 11, 14, 15) then maxmark = 6;The code is a bit less accessible, but now only 2000 if-statements need to be evaluated. But there is a third way:
else if item in (1, 5, 9, 13) then maxmark = 4;
else maxmark = 9;
select (item);This has the same computational load as the previous code using 'if else if', but it is clearer what is going on. Furthermore, you can be assured that this code is always the most computationally efficient.
when (1, 5, 9, 13) maxmark = 4;
when (2, 3, 6, 7, 10, 11, 14, 15) maxmark = 6;
when (4, 8, 12, 16) maxmark = 9; /* or: otherwise maxmark = 9 */
end;
0 Comments:
Post a Comment
<< Home