Tomas Vondra <tomas.vondra@2ndquadrant.com> writes:
> On Sun, Apr 19, 2020 at 11:24:38AM -0300, Ranier Vilela wrote:
>> strlen it is one of the low fruits that can be harvested.
> Maybe there are places where this would help, but I don't see a reason
> to just throw away all strlen calls and replace them with something
> clearly less convenient and possibly more error-prone (I'd expect quite
> a few off-by-one mistakes with this).
I've heard it claimed that modern compilers will optimize
strlen('literal') to a constant at compile time. I'm not sure how
much I believe that, but to the extent that it's true, replacing such
calls would provide exactly no performance benefit.
I'm quite -1 on changing these to sizeof(), in any case, because
(a) that opens up room for confusion about whether the trailing nul is
included, and (b) it makes it very easy, when changing or copy/pasting
code, to apply sizeof to something that's not a string literal, with
disastrous results.
The cases where Ranier proposes to replace strlen(foo) == 0
with a test on foo[0] do seem like wins, though. Asking for
the full string length to be computed is more computation than
necessary, and it's less clear that the compiler could be
expected to save you from that. Anyway there's a coding style
proposition that we should be doing this consistently, and
certainly lots of places do do this without using strlen().
I can't get excited about the proposed changes to optimize away
multiple calls of strlen() either, unless there's performance
measurements to support them individually. This again seems like
something a compiler might do for you.
regards, tom lane