Re: [PATCH] Small optimization across postgres (remove strlen duplicate usage)

From: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
To: Tomas Vondra <tomas(dot)vondra(at)2ndquadrant(dot)com>
Cc: Ranier Vilela <ranier(dot)vf(at)gmail(dot)com>, PostgreSQL Hackers <pgsql-hackers(at)lists(dot)postgresql(dot)org>
Subject: Re: [PATCH] Small optimization across postgres (remove strlen duplicate usage)
Date: 2020-04-19 21:38:03
Message-ID: 13847.1587332283@sss.pgh.pa.us
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-hackers

Tomas Vondra <tomas(dot)vondra(at)2ndquadrant(dot)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

In response to

Responses

Browse pgsql-hackers by date

  From Date Subject
Next Message David Rowley 2020-04-19 22:00:28 Re: [PATCH] Small optimization across postgres (remove strlen duplicate usage)
Previous Message Andreas Karlsson 2020-04-19 21:20:58 Re: [PATCH] Small optimization across postgres (remove strlen duplicate usage)