Subject: Re: [PATCH v3] skip_prefix: rewrite so that prefix is scanned once

From: David Kastrup <[email-masked]>
Date: Tue, 04 Mar 2014 01:09:39 +0100

Duy Nguyen <[email-masked]> writes:

> On Tue, Mar 4, 2014 at 5:43 AM, Junio C Hamano <[email-masked]> wrote:
>> diff --git a/git-compat-util.h b/git-compat-util.h
>> index cbd86c3..68ffaef 100644
>> --- a/git-compat-util.h
>> +++ b/git-compat-util.h
>> @@ -357,8 +357,14 @@ extern int suffixcmp(const char *str, const char *suffix);
>>
>>  static inline const char *skip_prefix(const char *str, const char *prefix)
>>  {
>> -       size_t len = strlen(prefix);
>> -       return strncmp(str, prefix, len) ? NULL : str + len;
>
> Just a note. gcc does optimize strlen("abcdef") to 6, and with that
> information at compile time built-in strncmp might do better.

Indeed, most (but not all) of the calls have a constant string as
prefix.  However, strncmp in each iteration checks for both *str as well
as *prefix to be different from '\0' independently (and it appears
unlikely to me that the optimizer will figure out that it's unnecessary
for either) _and_ compares them for equality so it's not likely to be
faster than the open-coded loop.

One could, however, use memcmp instead of strncmp.  I'm just not sure
whether memcmp is guaranteed not to peek beyond the first mismatching
byte even if the count would allow for more.  It could lead to undefined
behavior if the first mismatching byte would be the ending NUL byte of
str.

-- 
David Kastrup