TLDR Web Dev · ARTICLES & TUTORIALS

STRLCPY AND HOW CPUS CAN DEFY COMMON SENSE

nrk.neocities.org8 min read

Summary from the TLDR Web Dev newsletter

strlcpy is a string copying function that traverses the source string only once, compared to strlen + memcpy, which traverses it twice. While it seems intuitive that a single traversal should be faster, benchmarks show that the double traversal method is often significantly faster, particularly for larger strings. This is due to the fact that CPUs can execute independent instructions in parallel, and the memcpy loop in strlen + memcpy has fewer dependencies than the fused loop in strlcpy, allowing for greater parallelism.