Re: [PATCH 3/3] match_basename: use strncmp instead of strcmp
- From
Duy Nguyen <pclouds@gmail.com>
- Date
- Mar 9, 2013, 09:58 UTC
- Message-ID
- <CACsJy8D-ZJrC7n5ky9sc_UoenOLTg0h6tEczp=-U9ppn820P-g@mail.gmail.com>
- In-Reply-To
- <7v4nglf1w3.fsf@alter.siamese.dyndns.org>
On Sat, Mar 9, 2013 at 2:50 PM, Junio C Hamano <gitster@pobox.com> wrote:
Show 16 quoted lines
> Nguyễn Thái Ngọc Duy <pclouds@gmail.com> writes: > >> strncmp provides length information, compared to strcmp, which could >> be taken advantage by the implementation. Even better, we could check >> if the lengths are equal before calling strncmp, eliminating a bit of >> strncmp calls. > > I think I am a bit slower than my usual self tonight, but I am > utterly confused by the above. > > strncmp() compares _only_ up to the first n bytes, so when you are > using it for equality, it is not "we could check length", but is "we > MUST check they match to the length of the shorter string", if you > want to obtain not just faster but correct result. > > Am I mistaken?
Yeap, the description is a bit misleading. Although you could get away with length check by doing !strncmp(a, b, strlen(a)+1).
Show 9 quoted lines
> Even if you are using strcmp() that yields ordering not just > equality, it can return a correct result as soon as it hits the > first bytes that are different; I doubt using strncmp() contributes > to the performance very much. Comparing lengths before doing > byte-for-byte comparison could help because you can reject two > strings with different lengths without looking at them. > > At the same time, I wonder if we can take advantage of the fact that > these call sites only care about equality and not ordering.
I tried to push it further and compare hash before do the actual string comparison. It slowed things down (hopefully because the cost of hashing, the same one from name-hash.c, not because I did it wrong).
-- Duy