`Strlen` in Glibc
4 points by c4pt0r 1 year ago | 2 comments- simonblack 1 year agoThat seems so unnecessarily complex. However, I suppose it must work faster than a simple loop testing for the terminating NULL, counting as you go.
- swatcoder 1 year agoThat’s correct.
It’s kind of like a “poor man’s” SIMD, striding through four (to eight) null-checks at a time, using the processor’s native word size, and then decomposing the eventual hit to figure out which byte had the null.
strlen() is frequently used in applications, and often without much discipline, so this kind of optimization can have big payoff system-wide. Good comments help keep it legible despite the tricks.
You generally wouldn’t bother with something like this in an application unless you identified it as a hot path through profiling, but libraries (and especially standard libraries) can anticipate what needs attention and include many of these sorts of optimizations. They’re great code to study.
- swatcoder 1 year ago