This is an archive of the discontinued LLVM Phabricator instance.

[libc] Check pointer equality in strcmp, strncmp, and memcmp
Needs ReviewPublic

Authored by squidgyberries on Jan 27 2023, 1:28 AM.

Details

Reviewers
gchatelet
Group Reviewers
Restricted Project
Summary

Check if left and right point to the same location before looping through the bytes.

Diff Detail

Event Timeline

squidgyberries created this revision.Jan 27 2023, 1:28 AM
Herald added a project: Restricted Project. · View Herald TranscriptJan 27 2023, 1:28 AM
squidgyberries requested review of this revision.Jan 27 2023, 1:28 AM

This patch looks fine codewise, but do you have any numbers on what the performance impact will be for strings that are not pointer-equal?

#include "include/string.h"

int main(void) {
  for (unsigned long i = 0; i < 50000000000; ++i) strcmp("hello", "world");
  return 0;
}

I compiled this with clang 15.0.7 on my x64 Arch Linux machine with an Intel i7-12700H without optimizations. I ran it five times with the patch and five time without it and timed it with the time command. On average it ran for 12.8618 seconds with the patch and 12.8766 seconds without for me.

I suspect it is almost never the case that we call these functions with the same pointer on both sides.
In my opinion, this optimization is best done at the call site when the user suspects that it can actually happen.

For memfunction, we want to reduce the function's latency to a minimum so the check being in the hot path actually hinders performance.

So, codewise this patch is fine but I don't think we should submit it.

gchatelet resigned from this revision.Jul 18 2023, 5:57 AM