Search code examples
delphidelphi-xe6

Efficiently compare an integer against a static list of integers in Delphi?


Similarly to any way to compare an integer variable to a list of integers in if statement but in Delphi, how can I test whether an integer variable is contained in a static "list" (loosely speaking - a set that is predefined) of integers (maybe a list of consts, or a list of explicit values) in an if statement?

Now I would do something like this:

if (x = 1) or
   (x = 2263) or
   (x = 263553) or
   (x = whatever_int) then
begin
  //do something;
end;

But I'm trying to avoid lenghty sequences of or conditions.

I'm using Delphi XE6, so if there's something new to achieve this in a clean way, please advise me.


Solution

  • Your current approach is good. The compiler will produce efficient code. If efficiency is of the utmost importance, then you can choose the order of the comparisons so that the most common values are checked first. This requires knowledge of the distribution of your input data.

    Another syntactical approach is the case statement. For instance:

    case x of
    1, 2263, 263553, whatever_int:
      // do other stuff
    end;
    

    This results in similar (in fact I suspect identical) code to the if statement. But it is perhaps more concise and easier to read. And in some scenarios the compiler is able to produce a jump table.

    If efficiency is of the utmost importance to you then do make sure that you inspect the code that the compiler emits, for release compiler options, and perform profiling.

    I do wonder what you really mean by efficient. In programming that term has a specific meaning relating to runtime performance. But I wonder if you are actually more concerned with writing clear and concise code, in which case efficient is the wrong term. The fact that your question talks about avoiding repeated or operators makes me doubt that efficiency is what matters to you.

    On the other hand, if runtime performance is what matters then consider giving up on code clarity and implementing an indexed jump table. But don't ever optimise code without first identifying that it is a bottleneck, and profiling any changes you make.