ResourceString vs Constant
by: G.E. Ozz Nixon Jr.
Published: September 2009
©opyright 2009 by Friends of FPC
While cleaning up my FTP server code, changing common strings to constants -
I pondered which is faster, a constant or a resource string in Free Pascal?
The answer makes sense, but I was surprised how much faster...
Download resource.pas source
Uses
dxutil_environment;// contains TimeCounter for Windows, Linux and Mac
const
Str1='This is a constant string';
ResourceString
Str2='This is a resource string';
Var
Loop:Longint;
StartTime:Comp;
S:String;
Begin
StartTime:=Trunc(TimeCounter);
For Loop:=1 to 100000000 do S:=Str1;
System.Writeln('Constant: ',Trunc(Trunc(TimeCounter)-StartTime));
StartTime:=Trunc(TimeCounter);
For Loop:=1 to 100000000 do S:=Str2;
System.Writeln('Resource: ',Trunc(Trunc(TimeCounter)-StartTime));
StartTime:=Trunc(TimeCounter);
For Loop:=1 to 100000000 do S:='This is an inline string';
System.Writeln('inline: ',Trunc(Trunc(TimeCounter)-StartTime));
end.
The results on Linux, Constant: 7819 Resource: 4010, due to the design of
how a resource is addressed versus a constant, it takes roughly have the time
to work with a resource string than a constant.
On my Mac Book Pro the results were closer, Constant: 2781 Resource: 1949, but
obviously still worth the effort to clean-up some of my high performance
products to convert constants to resource strings.
After writing this page, I went back an added the "inline" to be closer to how
must people write their code (not using constants, but inline constant strings).
And I found that inline is even a little bit slower than a constant. So, for
those of you who want to see a slight improvement in code which does a lot
of text output (static text) it is worth revising your code to resource strings.
Plus if you ever decide to make your code multi-lingual, it will help you as
your can compile in/out different languages. I did this for my DXSock socket
suite back in the 90's.
G.E. Ozz Nixon Jr.