Which is faster - CASE or IF IF or IF ELSIF


#1

Hi,

I am busy going through my code looking at speed optimizing it.

I currently have (Some of my IF statements have 20 or more):

IF x = 1
END
IF x = 2
END
IF x = 3
END

I am wondering if CASE or ELSIF would be faster:

CASE x
OF 1
OF 2
OF 3
END

OR

IF x = 1
ELSIF x = 2
ELSIF x = 3
END

Any ideas and/or preferences would be appreciated.

Regards

Johan de Klerk


#2

First snippet is applicable if you have something like this:

IF x = 1
  x = 3
END

regarding 2nd and 3rd - better to look at assembler code to see the difference.


#3

At @Mike_Duglas said, look at the assembler
My guess is that they are all pretty close, (if not identical).

In this example (branching), I’m more concerned about the clarity of the code.

If all of them are comparing x, I would lean towards a CASE statement, as it it’s clearer.

I highly recommend reading “clean code” by Robert C Martin (aka Uncle Bob)

Here’s a link to an amazon page for Uncle Bob


#4

From the manual:

For those situations where the program’s logic could allow using either a CASE structure or a complex IF/ELSIF structure, the CASE structure will generally generate more efficient object code. EXECUTE generates the most efficient object code for those special cases where the condition evaluates to an integer in the range of 1 to n.


#5

Hi everyone,

Thank you very much for all your comments.

I am now see much clearer on this.

Regards

Johan de Klerk


#6

Johan,

Except in an extreme situation, as Mark suggests, clean code & readability should take precedence.
My guess is that you might need 100,000 plus loop cycles in an identical test to begin to see a noticeable time difference between IF & CASE.


#7

Last time I checked the Assembler code, a CASE was a bit faster. It depends on what type of variables are being used. But it is all executing in Ram and takes microseconds, so it will not make a noticable difference unless it is looped a million times. Most speed differences are found in the database commands or calls to the drive. Always optimize what is slowest, first. :sunglasses:


#8

Hi everyone,

I have decided to follow advice and go the CASE route for cleaner readability.

Thank you very much.
I appreciate all the advice and comments.

Regards

Johan de Klerk