This is the mail archive of the cygwin-patches mailing list for the Cygwin project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: avoid calling strlen() twice in readlink()


On 8 March 2012 19:48, Christian Franke <Christian.Franke@t-online.de> wrote:
> Corinna Vinschen wrote:
>>
>> On Mar Â8 08:29, Eric Blake wrote:
>>>
>>> On 03/08/2012 06:37 AM, VÃclav Zeman wrote:
>>>>
>>>> Hi.
>>>>
>>>> Here is a tiny patch to avoid calling strlen() twice in readlink().
>>>>
>>>>
>>>> - Âssize_t len = min (buflen, strlen (pathbuf.get_win32 ()));
>>>> + Âsize_t pathbuf_len = strlen (pathbuf.get_win32 ());
>>>> + Âsize_t len = MIN (buflen, pathbuf_len);
>>>> Â Âmemcpy (buf, pathbuf.get_win32 (), len);
>>>
>>> For that matter, is calling pathbuf.get_win32() twice worth factoring
>>> out?
>>
>> It's just a const char *pointer, and it's an inline method. ÂI'm pretty
>> sure the compiler will optimize this just fine.
>>
>>
>
> Yes - and it does ever more:
> strlen() is one of the compiler builtins declared with a const attribute
> internally. Then gcc optimizes duplicate calls away.
>
> Testcase:
>
> $ cat opt.cc
> #include <string.h>
>
> class X {
> Âconst char * p;
> Âpublic:
> Â ÂX();
> Â Âconst char * get() { return p; }
> };
>
> int f(X & x)
> {
> Âint i = 0;
> Âi += strlen(x.get());
> Âi += strlen(x.get());
> Âi += strlen(x.get());
> Âi += strlen(x.get());
> Âi += strlen(x.get());
> Âreturn i;
> }
>
> int g(X & x)
> {
> Âreturn 5 * strlen(x.get());
> }
>
>
> $ gcc -S -O2 -fomit-frame-pointer opt.cc
>
> $ cat opt.s | c++filt
> ...
> f(X&):
>    Âsubl  Â$28, %esp
>    Âmovl  Â32(%esp), %eax
>    Âmovl  Â(%eax), %eax
>    Âmovl  Â%eax, (%esp)
>    Âcall  Â_strlen
>    Âaddl  Â$28, %esp
>    Âleal  Â(%eax,%eax,4), %eax
> Â Â Â Âret
> ...
> g(X&):
>    Âsubl  Â$28, %esp
>    Âmovl  Â32(%esp), %eax
>    Âmovl  Â(%eax), %eax
>    Âmovl  Â%eax, (%esp)
>    Âcall  Â_strlen
>    Âaddl  Â$28, %esp
>    Âleal  Â(%eax,%eax,4), %eax
> Â Â Â Âret
>
> (interesting: With -O1 it uses an inline version of strlen, with -O2,3,...
> it doesn't)
>
>
> So this patch probably had no effect at all, sorry :-)
Heh, no problem. I really did not know GCC could do that these days.
The benefit seemed too obvious to let it pass :)

-- 
VZ


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]