Skip to content

Commit 56384e6

Browse files
René Scharfegitster
authored andcommitted
optimize compat/ memmem()
When memmem() was imported from glibc 2.2 into compat/, an optimization was dropped in the process, in order to make the code smaller and simpler. It was OK because memmem() wasn't used in performance-critical code. Now the situation has changed and we can benefit from this optimization. The trick is to avoid calling memcmp() if the first character of the needle already doesn't match. Checking one character directly is much cheaper than the function call overhead. We keep the first character of the needle in the variable named point and the rest in the one named tail. The following commands were run in a Linux kernel repository and timed, the best of five results is shown: $ STRING='Ensure that the real time constraints are schedulable.' $ git log -S"$STRING" HEAD -- kernel/sched.c >/dev/null On Windows Vista x64, before: real 0m8.470s user 0m0.000s sys 0m0.000s And after the patch: real 0m1.887s user 0m0.000s sys 0m0.000s Signed-off-by: Rene Scharfe <[email protected]> Signed-off-by: Junio C Hamano <[email protected]>
1 parent ce163c7 commit 56384e6

File tree

1 file changed

+4
-1
lines changed

1 file changed

+4
-1
lines changed

compat/memmem.c

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@ void *gitmemmem(const void *haystack, size_t haystack_len,
55
{
66
const char *begin = haystack;
77
const char *last_possible = begin + haystack_len - needle_len;
8+
const char *tail = needle;
9+
char point;
810

911
/*
1012
* The first occurrence of the empty string is deemed to occur at
@@ -20,8 +22,9 @@ void *gitmemmem(const void *haystack, size_t haystack_len,
2022
if (haystack_len < needle_len)
2123
return NULL;
2224

25+
point = *tail++;
2326
for (; begin <= last_possible; begin++) {
24-
if (!memcmp(begin, needle, needle_len))
27+
if (*begin == point && !memcmp(begin + 1, tail, needle_len - 1))
2528
return (void *)begin;
2629
}
2730

0 commit comments

Comments
 (0)