Re: [PATCH v4 08/14] libfdt: Speed up fdt_find_string_len_() with memchr()

From: Doug Anderson

Date: Mon Nov 23 2026 - 14:15:42 EST


Hi,

On Wed, Nov 18, 2026 at 9:38 PM David Gibson
<david@xxxxxxxxxxxxxxxxxxxxx> wrote:
>
> > Agreed. Since `p <= last` (`strtab + tabsize - (slen + 1)`), `p[slen]`
> > is always in bounds, and checking `!p[slen]` (i.e. `p[slen] == '\0'`)
> > before `memcmp(p, s, slen) == 0` cuts the `memcmp()` call count across
> > that 855-string replay from 187k down to 14.3k (the exact same 14.3k
> > `memcmp()` calls you'd get from scanning for `'\0'` with a `*p == *s`
> > pre-check, just with half as many `memchr()` stops).
> >
> > Timing 200 replays of that 855-string (11,259-byte) Qualcomm
> > `dt_strings` block with `gcc 15.2 -O2` on x86_64:
> > * Original (per-byte `memcmp`): 3.45 s
> > * Scan for `'\0'`, `memcmp(nul - slen, s, slen)`: 0.45 s
> > * Scan for `'\0'`, `*p == *s` then `memcmp`: 0.36 s
> > * Scan for `s[0]`, `memcmp` then `!p[slen]` (merged `c954f9dd8357`):
> > 0.27 s
> > * Scan for `s[0]`, `!p[slen]` then `memcmp`: 0.21 s (~20% faster)
> >
> > Since you already applied this patch to `main` (`c954f9dd8357`), so
> > I'll include a 1-line follow-up patch swapping the check order (with
> > `Suggested-by:` you) in v5.
>
> Uh.. "you" seems to be referring to two different people here. I
> applied the patch, David Laight suggested the optimization.

Whoops, that's embarassing. I definitely glazed over the last names.
Who could have expected two people named David?!? I will read more
carefully.


> Fwiw, since this further optimization is essentially free in terms of
> code complexity, I'm certainly happy to apply it. I am absolutely not
> keen on further micro-optimization of this.

OK, fair. Do you want me to drop the 1-line patch from my v5 draft
then? It's basically this:

- if (memcmp(p, s, slen) == 0 && p[slen] == '\0')
+ if (p[slen] == '\0' && memcmp(p, s, slen) == 0)

While it is a micro-optimization, the code is no harder to read so it
feels like a nice free speedup. ...but fine to drop it, too. ;-)

-Doug