Skip site navigation (1) Skip section navigation (2)

Faster StrNCpy

From: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
To: pgsql-hackers(at)postgreSQL(dot)org
Subject: Faster StrNCpy
Date: 2006-09-26 20:24:51
Message-ID: (view raw, whole thread or download thread mbox)
Lists: pgsql-hackerspgsql-patches
David Strong points out here
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

Next:From: Dragan ZubacDate: 2006-09-26 20:39:18
Subject: PostgreSQL HA questions
Previous:From: Markus SchaberDate: 2006-09-26 20:17:50
Subject: Re: Internal Transaction

pgsql-patches by date

Next:From: Martijn van OosterhoutDate: 2006-09-26 20:40:18
Subject: Re: Faster StrNCpy
Previous:From: Alvaro HerreraDate: 2006-09-26 17:41:00
Subject: Re: Too many messages from Autovacuum

Privacy Policy | About PostgreSQL
Copyright © 1996-2017 The PostgreSQL Global Development Group