Efficiency of methods "begins with substring" in Delphi?

How does the performance of these two ways of determining whether a string starts with a specific substring in Delphi work? Is it significantly faster / more efficient than the other?

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

against.

  if (AnsiStartsStr('=?', testString)) then ... 
+6
source share
3 answers

Well, the first one will certainly be faster. The solution to a hard-coded, very specific problem almost always goes much faster than transferring a specific solution to the overall problem of the solution. As for โ€œsignificantlyโ€ faster, why don't you check it out? Run both versions in a loop 10 million times and use TStopwatch (or something else if you don't have D2010 or newer) to have this time.

One more thing: the first is certainly faster, but it may be wrong. If length(TestString) not guaranteed to be> = 2, there may be an error condition. If TestString is an empty string, this will throw an exception. If not, you may or may not get an exception depending on the compiler settings.

+7
source

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; 
+4
source

The first in the CPU window is only mov , cmp and jnz (in the end it repeats once), and the second looks much more complicated (uses Copy and WinApi CompareString ). First you need to be faster.

+2
source

Source: https://habr.com/ru/post/906235/


All Articles