Re: [PATCH 1/2] lib/string: Improve strstarts() performance

From: Zijun Hu
Date: Tue Apr 08 2025 - 07:38:28 EST


On 2025/4/8 00:17, Kees Cook wrote:
>> strstarts() is frequently invoked to test if a string has another string
>> as prefix, but its performance is degraded by the strlen() loop contained.
>>
>> Improve its performance by eliminating the strlen() loop.
> So, as Andy already said: no, this is very unlikely to be a performance
> improvement, and if it is, you'll need to show the numbers (and likely
> the reason _why_, in the form of assembly output, etc).
>

agree.

> The reason this isn't going to be an improvement is because
> strlen($string_constant) is optimized by the compiler into a integral
> constant value. So you'd be replacing a potentially inline constant with

will confirm if strlen() within strstarts() is compile-time constant.

> an explicit function call. That will be much more expensive.

strstarts() has a strncmp() function call as well even if it is inline

>
> With almost 300 users:
> $ git grep 'strstarts' | wc -l
> 198
>
> Only 38 are _not_ using a string constant:
> $ git grep 'strstarts' | grep -v '"' | wc -l
> 38
>
> Additionally, there is no "loop". strlen() of a runtime string would be
> evaluated once.
>

strlen() contains a loop which has strlen() char comparisons

> -Kees