Faster StrNCpy

Поиск
Список
Период
Сортировка
От Tom Lane
Тема Faster StrNCpy
Дата
Msg-id 29452.1159302291@sss.pgh.pa.us
обсуждение исходный текст
Ответы Re: Faster StrNCpy  (Martijn van Oosterhout <kleptog@svana.org>)
Список 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 по дате отправления:

Предыдущее
От: Markus Schaber
Дата:
Сообщение: Re: Internal Transaction
Следующее
От: Martijn van Oosterhout
Дата:
Сообщение: Re: Faster StrNCpy