SizeOf() vs Constants
by: G.E. Ozz Nixon Jr.
Published: August 2009
©opyright 2009 by Friends of FPC
While working interpreters (PaxCompiler and DECLAN), I realized we use SizeOf(type) very often. Recently, while
migrating to other compilers and operating systems, we had to address FPC's Integer 16bit vs FPC's Integer 32bit.
So, I had to touch all of the code for LongInt to enforce 32bit for consistancy. Anyway, I became curious if
all of these SizeOf() calls were slower that having predefined constants. In short, no... here is my test code:
Download sizeof.pas source
Uses
dxutil_environment;// contains TimeCounter for Windows, Linux and Mac
const
LongWordSize = SizeOf(LongWord);
LongWordSizeX2 = SizeOf(LongWord)*2;
Var
Loop:LongWord;
StartTime:Comp;
X:Longint;
Begin
StartTime:=Trunc(TimeCounter);
For Loop:=1 to 100000000 do X:=SizeOf(LongWord);
System.Writeln(Trunc(Trunc(TimeCounter)-StartTime));
StartTime:=Trunc(TimeCounter);
For Loop:=1 to 100000000 do X:=LongWordSize;
System.Writeln(Trunc(Trunc(TimeCounter)-StartTime));
StartTime:=Trunc(TimeCounter);
For Loop:=1 to 100000000 do X:=SizeOf(LongWord)*2;
System.Writeln(Trunc(Trunc(TimeCounter)-StartTime));
StartTime:=Trunc(TimeCounter);
For Loop:=1 to 100000000 do X:=LongWordSizeX2;
System.Writeln(Trunc(Trunc(TimeCounter)-StartTime));
end.
Oddly, the SizeOf() code is actually a millisecond or two faster (over 100 million calls).
G.E. Ozz Nixon Jr.