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 ...
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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With