FreePascal Information Logo Friend of FreePascal Compiler Title
Articles with Feedback, FPC News Library, PDF Collection, Mail Lists, Books, Newsgroups, IRC Open online discussion areas Research and Tutorials Tools, Compilers and Utilities Blurbs about us, advertising, etc.
Welcome to the FoFPC Research Notes: "CASE vs IF"

CASE vs IF

by: G.E. Ozz Nixon Jr.
Published: August 2009
©opyright 2009 by Friends of FPC



      A few years ago, I redesigned my socket suite (DXSock) to use CASE statements versus if statements everywhere I could. Now, I am migrating everything to cross platform, Windows, Linux and Mac OS X - I decided to present a test and it's results for all to see.

    Download Source IconDownload case.pas source
Uses
   dxutil_environment;// contains TimeCounter for Windows, Linux and Mac

Var
   Loop:LongWord;
   StartTime:Comp;
   X,Y:Integer;

Begin
   X:=3;
   Y:=0;
   StartTime:=Trunc(TimeCounter);
   For Loop:=1 to 100000000 do begin
      If X=1 then begin
         Y:=X;
      end
      else if X=3 then begin
         Y:=X+3;
      end;
   end;
   System.Writeln(Trunc(Trunc(TimeCounter)-StartTime));

   X:=3;
   Y:=0;
   StartTime:=Trunc(TimeCounter);
   For Loop:=1 to 100000000 do begin
      Case X of
         1:Begin
            Y:=X;
         End;
         3:Begin
            Y:=X+3;
         End;
      End;
   end;
   System.Writeln(Trunc(Trunc(TimeCounter)-StartTime));

end.

    On my MacBook Pro, the "if" logic took 444ms for 100 million iterations, while the case statement only took 352ms for 100 million iterations. Yet, the same code compiled and ran on this Linux web server took 593ms for the "if" logic and 664ms for the case statement. So, I added another "else if" and element to the case statement and then the case statement was faster by 80ms. So, when you have "deeper" if statements, case will be faster, however... apply logic to your code, if the first comparison of the if is what your code will hive the majority of the time, then definity use if else/if.

G.E. Ozz Nixon Jr.
 Links and Products we find useful



ButtonGenerator.com
Valid XHTML 1.0 Transitional Internet Map
Programmer's Heaven
grat-i-fi-ca-tion - noun
the state of being gratified; great satisfaction.


I am very happy to see that FoFPC is alive, we need more developers working on this great language.
Matias Vara
toro.sourceforge.net
Locations of visitors to this page world map hits counter
Copyright 2009 by 3F, LLC. All rights reserved. Worldwide.
Your request was processed by server #3 in 0.002444 secs.

sponsor
This sponsor helps us with our documentation