Faster Code for Delphi's Pos Function

  October 24, 2006

In his book, “The Tomes of Delphi Algorithms and Data Structures”, Julian Bucknall wrote that programmers do not pay enough attention to symbols and strings. Typecasting is performed by the compiler, so, quite often, a programmer does not even know what binary code is executed for the code he (or she) wrote. However, knowing this may help you create faster code. For instance, Delphi's Pos function can work faster.

This function searches for a substring within another string and returns the substring's position in that string. If you use Pos to search for a character --



i := Pos('w', 'Hello, world!');

-- the compiler generates the binary code that transforms the character to a string and then searches for this string within another one. You can check this yourself by exploring the function's binary code in AQtime's Disassembler panel:

Julian says that the following routine searches for a character faster than Pos. It works faster despite the fact that it is written in Pascal, not in Assembler:

function TDPosCh(aCh: AnsiChar; const S: String): Integer;
i: Integer;
Result := 0;
for i := 1 to Length(S) do if (S[i] = aCh) then begin
Result := i;

The statement that this code works faster than Pos looks doubtful, so I decided to verify it with AQtime. I created a simple Delphi application that calls the Delphi version and  the custom version of the Pos function. To make the measurement results consistent, I called these functions 10,000 times in a loop.

Then I profiled this application with AQtime and, frankly speaking, I was surprised with the results. On my computer, a P4 2.6 GHz, 1Gb RAM, the custom function worked 6-10 times (!) faster than its VCL variant:

Click to display image

Of course, the custom function does not cover all the functionality of Pos (it searches for a single character, not for a substring). However, if your application performs lots of character searching operations, the custom variant may help you improve the application performance, and with AQtime at hand, you can always decide which variant is better.