Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficiency of "begins with substring" techniques in Delphi?

How does the performance of these two ways of determining whether a string begins with a certain substring in Delphi compare? Is one significantly faster/more efficient than the other?

  if ((testString[1] = '=') AND (testString[2] = '?')) then ...

vs.

  if (AnsiStartsStr('=?', testString)) then ...
like image 263
Jessica Brown Avatar asked Jan 17 '12 21:01

Jessica Brown


2 Answers

Well, the first will definitely be faster. Solving a hard-coded, highly specific problem almost always goes a lot faster than passing a specific solution to a general-problem-solving routine. As for "significantly" faster, why don't you test it? Run both versions it in a loop 10 million times and use TStopwatch (or something else if you don't have D2010 or later) to time it.

One other thing: The first is definitely faster, but it might also be wrong. If length(TestString) is not guaranteed to be >= 2, you could have an error condition here. If TestString is an empty string, this will raise an exception. If not, you may or may not get an exception depending on compiler settings.

like image 73
Mason Wheeler Avatar answered Nov 15 '22 08:11

Mason Wheeler


If you need speed with flexibility you can try something like:

function StatsWith(const SubStr, Str: string): Boolean; inline;
begin
  if Length(SubStr) <= Length(Str) then
    Result := CompareMem(Pointer(SubStr), Pointer(Str), ByteLength(SubStr))
  else
    Result := False;
end;
like image 26
arthurprs Avatar answered Nov 15 '22 08:11

arthurprs