[Asterisk-Dev] [RFC] strncpy -> ast_copy_string

Steve Kann stevek at stevek.com
Sun May 1 18:51:26 MST 2005


On May 1, 2005, at 9:31 PM, Kevin P. Fleming wrote:

> The recent UTF-8 discussion brought to light something that I had not 
> realized before... strncpy() zero-fills the destination buffer, which 
> is waste of time (and cache pollution). In Asterisk, we are nearly 
> always copying strings into buffers that are much larger than 
> required, so this extra zero-writing is just wasted CPU cycles.
>
> I've committed an ast_copy_string() function that works the same way 
> as strncpy() except for three differences:
>
> - there is no return value (of the nearly 1,300 uses of strncpy in CVS 
> HEAD, only two use the return value)
> - it guarantees that the output buffer will be null-terminated
> - it does not null-pad the output buffer
>
> I tested a simple search/replace conversion of chan_sip with no ill 
> effects, and the resulting .so file was slightly (a few hundred bytes) 
> smaller. No modules in Asterisk have actually been converted yet, 
> though.
>
> I do understand that GCC has a highly-optimized strncpy implementation 
> for each architecture it runs on, and I don't doubt that an open-coded 
> version will not be optimized as well. However, we'd be trading a 
> slightly slower implementation against not writing many, many billions 
> of excess zero bytes over the lifetime of an Asterisk instance.

You can at least do a simple processor-independent optimization of 
this, by copying long int-sized chunks of the string separately; here's 
a sample of this:

http://www.koders.com/c/fid75DA39E03FCB2787FB2897C252B0A28F3D177937.aspx

I don't know if that implementation is faster or not;  I guess it 
depends on the common length of strings.  (of course, you can still 
remove the zero-fill, and add the termination bits..).

-SteveK




More information about the asterisk-dev mailing list