Delphi Performance: Case Versus If

Posted by Andreas Rejbrand on Stack Overflow See other posts from Stack Overflow or by Andreas Rejbrand
Published on 2010-03-30T16:59:21Z Indexed on 2010/03/30 17:03 UTC
Read the original article Hit count: 270

Filed under:
|
|
|

I guess there might be some overlapping with previous SO questions, but I could not find a Delphi-specific question on this topic.

Suppose that you want to check if an unsigned 32-bit integer variable "MyAction" is equal to any of the constants ACTION1, ACTION2, ... ACTIONn, where n is - say 1000. I guess that, besides being more elegant,

case MyAction of
  ACTION1: {code};
  ACTION2: {code};
  ...
  ACTIONn: {code};
end;

if much faster than

if MyAction = ACTION1 then
  // code
else if MyAction = ACTION2 then
  // code
...
else if MyAction = ACTIONn then
  // code;

I guess that the if variant takes time O(n) to complete (i.e. to find the right action) if the right action ACTIONi has a high value of i, whereas the case variant takes a lot less time (O(1)?).

  1. Am I correct that switch is much faster?
  2. Am I correct that the time required to find the right action in the switch case actually is independent of n? I.e. is it true that it does not really take any longer to check a million cases than to check 10 cases?
  3. How, exactly, does this work?

© Stack Overflow or respective owner

Related posts about delphi

Related posts about case