Jessica Brown
Jessica Brown

Reputation: 8312

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 ...

Upvotes: 6

Views: 4489

Answers (3)

arthurprs
arthurprs

Reputation: 4627

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;

Upvotes: 4

Pol
Pol

Reputation: 5134

The first in CPU window is just mov, cmp and jnz (eventually repeated one time) while the second looks far more complicated (uses Copy and WinApi's CompareString). First should be faster.

Upvotes: 2

Mason Wheeler
Mason Wheeler

Reputation: 84550

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.

Upvotes: 8

Related Questions