Re: Should we use MemSet or {0} for struct initialization?

From: Junwang Zhao <zhjwpku(at)gmail(dot)com>
To: John Naylor <john(dot)naylor(at)enterprisedb(dot)com>
Cc: Richard Guo <guofenglinux(at)gmail(dot)com>, PostgreSQL-development <pgsql-hackers(at)postgresql(dot)org>
Subject: Re: Should we use MemSet or {0} for struct initialization?
Date: 2023-08-31 11:35:32
Message-ID: CAEG8a3J=OeqWWtYA+6zswt+JspsGUZCvqNZni1qbBDKH-3K1OA@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-hackers

On Thu, Aug 31, 2023 at 7:07 PM John Naylor
<john(dot)naylor(at)enterprisedb(dot)com> wrote:
>
> > On Thu, Aug 31, 2023 at 5:34 PM Richard Guo <guofenglinux(at)gmail(dot)com> wrote:
> > >
> > > While working on a bug in expandRecordVariable() I noticed that in the
> > > switch statement for case RTE_SUBQUERY we initialize struct ParseState
> > > with {0} while for case RTE_CTE we do that with MemSet. I understand
> > > that there is nothing wrong with this, just cannot get away with the
> > > inconsistency inside the same function (sorry for the nitpicking).
> > >
> > > Do we have a preference for how to initialize structures? From 9fd45870
> > > it seems that we prefer to {0}. So here is a trivial patch doing that.
>
> It seems to have been deliberately left that way in the wake of that commit, see:
>
> https://www.postgresql.org/message-id/87d2e5f8-3c37-d185-4bbc-1de163ac4b10%40enterprisedb.com
>
> (If so, it deserves a comment to keep people from trying to change it...)
>
> > > And with a rough scan the MemSet calls in pg_stat_get_backend_subxact()
> > > can also be replaced with {0}, so include that in the patch too.
>
> I _believe_ that's harmless to change.
>
> On Thu, Aug 31, 2023 at 4:57 PM Junwang Zhao <zhjwpku(at)gmail(dot)com> wrote:
>
> > If the struct has padding or aligned, {0} only guarantee the struct
> > members initialized to 0, while memset sets the alignment/padding
> > to 0 as well, but since we will not access the alignment/padding, so
> > they give the same effect.
>
> See above -- if it's used as a hash key, for example, you must clear everything.

Yeah, if memcmp was used as the key comparison function, there is a problem.

>
> > I bet {0} should be faster since there is no function call, but I'm not
> > 100% sure ;)
>
> Neither has a function call. MemSet is a PG macro. You're thinking of memset, the libc library function, but a decent compiler can easily turn that into something else for fixed-size inputs.

good to know, thanks.

>
> --
> John Naylor
> EDB: http://www.enterprisedb.com
>
>

--
Regards
Junwang Zhao

In response to

Responses

Browse pgsql-hackers by date

  From Date Subject
Next Message John Naylor 2023-08-31 11:41:14 Re: Replace some cstring_to_text to cstring_to_text_with_len
Previous Message Aleksander Alekseev 2023-08-31 11:34:26 Re: Commitfest 2023-09 starts soon