Faster StrNCpy - Mailing list pgsql-hackers

From Tom Lane
Subject Faster StrNCpy
Date
Msg-id 29452.1159302291@sss.pgh.pa.us
Whole thread Raw
Responses Re: Faster StrNCpy  (Martijn van Oosterhout <kleptog@svana.org>)
List pgsql-hackers
David Strong points out here
http://archives.postgresql.org/pgsql-hackers/2006-09/msg02071.php
that some popular implementations of strncpy(dst,src,n) are quite
inefficient when strlen(src) is much less than n, because they don't
optimize the zero-pad step that is required by the standard.

It looks to me like we have a good number of places that are using
either StrNCpy or strncpy directly to copy into large buffers that
we do not need full zero-padding in, only a single guaranteed null
byte.  While not all of these places are in performance-critical
paths, some are.  David identified set_ps_display, and the other
thing that's probably significant is unnecessary use of strncpy
for keys of string-keyed hash tables.  (We used to actually need
zero padding for string-keyed hash keys, but that was a long time ago.)

I propose adding an additional macro in c.h, along the lines of

#define StrNCopy(dst,src,len) \   do \   { \       char * _dst = (dst); \       Size _len = (len); \
\       if (_len > 0) \       { \           const char * _src = (src); \           Size _src_len = strlen(_src); \
\           if (_src_len < _len) \               memcpy(_dst, _src, _src_len + 1); \           else \           { \
         memcpy(_dst, _src, _len - 1); \               _dst[_len-1] = '\0'; \           } \       } \   } while (0)
 

Unlike StrNCpy, this requires that the source string be null-terminated,
so it would not be a drop-in replacement everywhere.  Also, it could be
a performance loss if strlen(src) is much larger than len ... but that
is not usually the case for the places we'd want to apply it.

Thoughts, objections?  In particular, is the name OK, or do we need
something a bit further away from StrNCpy?
        regards, tom lane


pgsql-hackers by date:

Previous
From: Markus Schaber
Date:
Subject: Re: Internal Transaction
Next
From: Martijn van Oosterhout
Date:
Subject: Re: Faster StrNCpy