Live data from Hacker News

Glibc's strlen implementation: Probably not what you'd guess

sources.redhat.com

71–74 of 74 posts

Re: Glibc's strlen implementation: Probably not what you'd guess

#71

That makes the X86 assembly version look straightforward: http://www.int80h.org/strlen/ . I think it is just a fallback implementation that is used when no optimized version has been created for the target processor. Every time I've looked my compiler has used a hand-optimized version for every platform. Quite possibly, this is 100% dead code.

That looks like a pretty straightforward translation of the basic while (d++ = s++); code. It uses higher-level instructions, but those probably get microcoded to the same thing anyway. (Note: my information on the inner workings of x86 CPUs may be a bit dated.)

Re: Glibc's strlen implementation: Probably not what you'd guess

#72
post #43
post #3

It's cute. Will I employ similar technique in my own code? Absolutely not. It hinders readability and byte comparison instructions in consecutive memory addresses are so stupidly fast that I'll probably save less CPU time combined in all executions of my program than the total amount of time it took me to think this hack up. If you're a maintainer of glibc though (which is known for its exceptionally clear and straig…

In places where I've done this sort of thing, I prefer #ifdef NO_CLEVER_OPTIMIZATIONS obvious version #else complicated fast version #endif It's good as documentation, good as a test case, and good for isolating weird problems like compiler optimization bugs.

Agreed, that's a great way to handle the case

Re: Glibc's strlen implementation: Probably not what you'd guess

#74
post #22

The lesson here is use library functions . Someone smarter than you has probably optimized the hell out of them.

Indeed, in college I was interviewing for a job, and the interviewer asked how I would determine the length of a null terminated string, and I thought I nailed it by giving a typical "while(*(str++)) c++;" implementation. The "right" answer was just to use strlen()...

I had a job interview once where the question was "find all descendants of a DOM node with a certain tag name, and return them in document order." I thought for about 30 seconds, and then wrote up on the board:

    element.getElementsByTagName(tagName);
That was what he was looking for. ;-) Of course, then he had me do it out as if getElementsByTagName didn't exist.
Post reply on HN