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 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.