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. IfTestStringis an empty string, this will raise an exception. If not, you may or may not get an exception depending on compiler settings.