In vs If
by: G.E. Ozz Nixon Jr.
Published: August 2009
©opyright 2009 by Friends of FPC
After doing the benchmark of For Loop "Up" vs "DownTo", I decided why not evalute which
is faster, testing a char using "in" versus two "if" statements. The results vary a lot
depending upon Linux versus Mac.
Download in.pas source
Uses
dxutil_environment;// contains TimeCounter for Windows, Linux and Mac
Var
Loop:LongWord;
StartTime:Comp;
S,Result:AnsiString;
Loop2:LongInt;
Begin
S:='AbCdEfGhIjKlMnOpQrStUvWxYz';
Writeln('Uppercase()');
StartTime:=Trunc(TimeCounter);
For Loop:=1 to 100000000 do begin
Result:=S;
for Loop2 := Length(Result) downto 1 do
if Result[Loop2] in ['a'..'z'] then Dec(Result[Loop2], 32);
end;
System.Write('In ',Trunc(Trunc(TimeCounter)-StartTime));
StartTime:=Trunc(TimeCounter);
For Loop:=1 to 100000000 do begin
Result:=S;
for Loop2 := Length(Result) downto 1 do
if (Ord(Result[Loop2])>=Ord('a')) and
(Ord(Result[Loop2])<=Ord('z')) then Dec(Result[Loop2], 32);
end;
System.Writeln(' If ',Trunc(Trunc(TimeCounter)-StartTime));
end.
The results on Linux, In 38842 If 25977... show us that the "if" logic is a lot faster
than using "in". Yet, the results on a Mac, In 29686 If 31833... show us that the "in"
logic is a little faster than the "if" logic.
G.E. Ozz Nixon Jr.