[Date Prev][Date Next] [Chronological] [Thread] [Top]

Re: ideas for improving slapd



> 2.) There are quite some instances of code similar to the following
> naive strdup implementation, usually somewhat more complicated:
>
>     foo=malloc(strlen(bar)+1);
>     strcpy(foo,bar);
>
> A while ago while implementing an EXPRESS compiler which naturally
> deals with quite some strdups i found that replacing my naive strdup
> implemented in the style above by the following code improved
> performance by nearly 10%:
>
>    int len=strlen(bar)+1;
>    foo=malloc(len);
>    memcpy(foo,bar,len);
>
> This is most likely because strcpy at first scans the string for the
> terminating zero and then uses a blockmove with known length for
> the copy, which results in an extra scan of the string. I learned to
> keep track of string lengths and to avoid almost always strcpy,
> strcat and many strcmps, replacing them by memcpy (or bcopy for BSD
> fans) and memcmp, and of course i used `sizeof' for string constants.
> This proved very useful in an reimplementation of a real time data
> processing program.

I thought I'd run a couple tests on your idea here and discovered some
things.

I wrote a program! =) The test program had four loop constructs.  The
first construct ran an strdup() on a static string and freed the
memory.  The second contruct did the same thing, but called strdup1
which used the malloc()/strcpy() combo described above.  The third used
strlen()/malloc()/memcpy() and the fourth was a macro implementing the
malloc()/strcpy() contruct.  Each loop executed 1,000,000 times.
Compiler was egcs, hardware was PPro/200 SMP, 192 Meg o' ram running
Linux v2.0.36.

Stuff I learned:
1) strdup() is SLOW!  Its performance was consistent, no matter how I
compiled the test program.  (makes sense since there's really nothing to
optimize there.)
2) the strlen()/malloc()/memcpy() was the next fastest, but not by much.
(maybe 2%)
3) malloc()/strcpy() was next fastest, showing about a 10% improvement
4) the macro was clearly the fastest, no doubt about it.  50%
improvement from strdup() alone.

I'd be more than happy to give up the test program.  The macro was
implemented as:
#define strdup3(x) (x?strcpy(malloc(strlen(x)+1),x):NULL)

One thing I should probably mention is that all functions/macros I wrote
check the incoming string to see if it is null.  strdup() as implemented
under Linux will segfault if it is passed a NULL pointer.

d