From 15cd01ef053df8583773701ec71dc1af03c863c7 Mon Sep 17 00:00:00 2001 From: minelogy <72928567+minelogy-dev@users.noreply.github.com> Date: Sun, 1 Nov 2026 07:56:32 -0800 Subject: [PATCH 01/10] perf: filter forward search candidates before KMP Use bounded endpoint probes and native short-pattern search while retaining portable KMP for longer needles. Exercise native and fallback paths with binary differential tests and compare against the baseline on one runner. Co-authored-by: Codex --- .github/scripts/compare-search.py | 146 +++++++++++++++++++++++ .github/workflows/search-performance.yml | 78 ++++++++++++ src/sx_core.c | 48 +++++++- tests/find_differential.c | 13 ++ tests/find_differential.h | 124 +++++++++++++++++++ tests/find_differential_fallback.c | 14 +++ 6 files changed, 421 insertions(+), 2 deletions(-) create mode 100644 .github/scripts/compare-search.py create mode 100644 .github/workflows/search-performance.yml create mode 100644 tests/find_differential.c create mode 100644 tests/find_differential.h create mode 100644 tests/find_differential_fallback.c diff --git a/.github/scripts/compare-search.py b/.github/scripts/compare-search.py new file mode 100644 index 0000000..304af56 --- /dev/null +++ b/.github/scripts/compare-search.py @@ -0,0 +1,146 @@ +#!/usr/bin/env python3 +"""Same-host before/after check; timing is evidence, not a noisy merge gate.""" +import csv +import importlib.util +import json +import os +from pathlib import Path +import shutil +import statistics + +ROOT = Path(__file__).resolve().parents[2] +WORK = ROOT / "build/search-performance" +BASELINE = "452314a7ca51f90a7a8fa66930947164af8fc4f6" +HARNESS = "ecf31d3d65a45466222dfb0f358e176a22d1bc1c" + +def main(): + harness = WORK / "harness" + spec = importlib.util.spec_from_file_location("baseline_bench", harness / "benchmarks/run.py") + bench = importlib.util.module_from_spec(spec) + spec.loader.exec_module(bench) + assert bench.output(["git", "rev-parse", "HEAD"], WORK / "before") == BASELINE + assert bench.output(["git", "rev-parse", "HEAD"], harness) == HARNESS + deps = WORK / "deps" + for lib, sha in bench.PINS.items(): + assert bench.output(["git", "rev-parse", "HEAD"], deps / lib) == sha + after = WORK / "after" + for folder in ("src", "include"): + shutil.copytree(ROOT / folder, after / folder, dirs_exist_ok=True) + + # Extend the existing 28 cases with common endpoint bytes, misses + # across the private cutoff, and repetitive text with both bytes present. + source = (harness / "benchmarks/strings.c").read_text() + source = source.replace("RESERVED = 16", "RESERVED = 16, COMMON = 32, PERIODIC = 64, END_PRESENT = 128") + anchor = ' {"copy_cstr_16"' + extra = [ + ("common8_miss_65536", 8, "COMMON"), + ("common8_end_65536", 8, "COMMON | HIT_END"), + ("periodic8_miss_65536", 8, "PERIODIC"), + ("common31_miss_65536", 31, "COMMON"), + ("common32_miss_65536", 32, "COMMON"), + ("common33_miss_65536", 33, "COMMON"), + ("repeated128_end_present_miss_65536", 128, "REPEATED | END_PRESENT"), + ("common257_miss_65536", 257, "COMMON"), + ] + assert anchor in source + source = source.replace(anchor, "".join( + f' {{"{name}", FIND, 65536, {m}, {flags}}},\n' + for name, m, flags in extra) + anchor, 1) + anchor = " f->sep = " + assert anchor in source + setup = """ + if (c->op == FIND) { + if (c->flags & COMMON) + for (size_t i = 0; i < m; ++i) f->needle[i] = (char)('a' + i % 25); + if (c->flags & PERIODIC) { + for (size_t i = 0; i < c->n; ++i) f->data[i] = i % 2 ? 'b' : 'a'; + memset(f->needle, 'a', m); + f->needle[m - 1] = 'b'; + } + if (c->flags & END_PRESENT) + for (size_t i = m - 2; i < c->n; i += m - 1) f->data[i] = 'b'; + if (c->flags & HIT_FRONT) memcpy(f->data, f->needle, m); + if (c->flags & HIT_END) memcpy(f->data + c->n - m, f->needle, m); + } +""" + source = source.replace(anchor, setup + anchor, 1) + for variant in ("before", "after"): + folder = WORK / variant / "benchmarks" + folder.mkdir(parents=True, exist_ok=True) + (folder / "strings.c").write_text(source) + + cpu = min(os.sched_getaffinity(0)) + out = WORK / "results" + out.mkdir(parents=True, exist_ok=True) + metadata = { + "before": BASELINE, "after": bench.output(["git", "rev-parse", "HEAD"], ROOT), + "harness": HARNESS, "dependencies": bench.PINS, + "pinned_cpu": cpu, "lscpu": json.loads(bench.output(["lscpu", "-J"])), + "libc": bench.output(["ldd", "--version"]).splitlines()[0], + "timing_flags": bench.COMMON + ["-O3", "-DNDEBUG"], + "samples": 11, "target_sample_ns": 20000000, + "note": "Variants run sequentially on the same pinned CPU. Hosted-runner scheduling and frequency remain uncontrolled.", + } + (out / "environment.json").write_text(json.dumps(metadata, indent=2) + "\n") + (out / "strings.c").write_text(source) + print("SEARCH_COMPARE_ENV=" + json.dumps(metadata), flush=True) + report = ["# Search before/after", "", + "Same job, pinned CPU, -O3, no LTO; medians of 11 hot-input samples.", + "Sequential runs are subject to host scheduling/frequency changes; small differences are inconclusive.", ""] + env = os.environ.copy() + env.update(ASAN_OPTIONS="detect_leaks=1:halt_on_error=1", + UBSAN_OPTIONS="halt_on_error=1:print_stacktrace=1") + for ci, cc in enumerate(("gcc-14", "clang-19")): + results = {} + for variant in (("before", "after") if ci == 0 else ("after", "before")): + bench.ROOT = WORK / variant + folder = out / cc / variant + folder.mkdir(parents=True, exist_ok=True) + log = folder / "commands.log" + check = bench.compile_binary(cc, folder / "check", "check", deps, log) + bench.invoke([str(check), "--check"], log, env=env, cpu=cpu) + binary = bench.compile_binary(cc, folder / "timing", "timing", deps, log) + bench.invoke([str(binary)], log, stdout=folder / "samples.csv", cpu=cpu) + alloc = bench.compile_binary(cc, folder / "alloc", "alloc", deps, log) + bench.invoke([str(alloc)], log, stdout=folder / "allocations.csv", cpu=cpu) + rows = list(csv.DictReader((folder / "samples.csv").open())) + memory = {(r["case"], r["library"]): r + for r in csv.DictReader((folder / "allocations.csv").open())} + groups = {} + for r in rows: + groups.setdefault((r["case"], r["library"]), []).append(float(r["ns_per_op"])) + assert len(groups) == 82 + len(extra) * 3, len(groups) + stats = {} + for (case, library), values in groups.items(): + assert len(values) == 11 + stats[case, library] = { + "case": case, "library": library, + "median_ns": statistics.median(values), + "p10_ns": bench.quantile(values, .1), "p90_ns": bench.quantile(values, .9), + "malloc_calls": int(memory[case, library]["malloc_calls"]), + } + (folder / "summary.json").write_text(json.dumps(list(stats.values()), indent=2) + "\n") + results[variant] = stats + report += [f"## {bench.output([cc, '--version']).splitlines()[0]}", "", + "| Case | Before ns | After ns | Before/after | After malloc calls |", + "| --- | ---: | ---: | ---: | ---: |"] + compared = [] + for key, before in sorted(results["before"].items()): + case, library = key + if not library.startswith("StringX"): + continue + after_row = results["after"][key] + ratio = before["median_ns"] / after_row["median_ns"] + row = {"case": case, "before": before, "after": after_row, "speedup": ratio} + compared.append(row) + report.append(f"| {case} | {before['median_ns']:.2f} | {after_row['median_ns']:.2f} | {ratio:.2f}x | {after_row['malloc_calls']} |") + print("SEARCH_COMPARE_JSON=" + json.dumps({"compiler": cc, "results": compared}), flush=True) + report.append("") + text = "\n".join(report) + "\n" + (out / "summary.md").write_text(text) + if os.environ.get("GITHUB_STEP_SUMMARY"): + with open(os.environ["GITHUB_STEP_SUMMARY"], "a") as dest: + dest.write(text) + +if __name__ == "__main__": + main() diff --git a/.github/workflows/search-performance.yml b/.github/workflows/search-performance.yml new file mode 100644 index 0000000..998feab --- /dev/null +++ b/.github/workflows/search-performance.yml @@ -0,0 +1,78 @@ +name: Search performance + +on: + pull_request: + paths: + - 'src/sx_core.c' + - '.github/scripts/compare-search.py' + - '.github/workflows/search-performance.yml' + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: search-performance-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + +defaults: + run: + shell: bash + +jobs: + benchmark: + name: Search before and after (GCC and Clang) + runs-on: ubuntu-24.04 + timeout-minutes: 25 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ github.event.pull_request.head.sha || github.sha }} + persist-credentials: false + - name: Install benchmark compilers and PCRE2 headers + timeout-minutes: 5 + run: | + if test -f /etc/apt/apt-mirrors.txt; then + printf '%s\n' 'https://archive.ubuntu.com/ubuntu' | sudo tee /etc/apt/apt-mirrors.txt > /dev/null + fi + sudo apt-get -o Acquire::Retries=3 -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 update + sudo env DEBIAN_FRONTEND=noninteractive apt-get \ + -o DPkg::Lock::Timeout=120 -o Acquire::Retries=3 \ + -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 \ + install --no-install-recommends -y gcc-14 clang-19 libclang-rt-19-dev libpcre2-dev pkg-config + - name: Check out the library baseline + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: 452314a7ca51f90a7a8fa66930947164af8fc4f6 + path: build/search-performance/before + persist-credentials: false + - name: Check out the immutable benchmark harness + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ecf31d3d65a45466222dfb0f358e176a22d1bc1c + path: build/search-performance/harness + persist-credentials: false + - name: Check out pinned SDS + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + repository: antirez/sds + ref: 5347739b1581fcba74fd5cab1fc21d2aef317d71 + path: build/search-performance/deps/sds + persist-credentials: false + - name: Check out pinned bstrlib + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + repository: websnarf/bstrlib + ref: f0ff1e808102a42cdc7204a4bb6fe231a24c4546 + path: build/search-performance/deps/bstrlib + persist-credentials: false + - name: Validate, measure and report on one pinned CPU + run: python3 .github/scripts/compare-search.py + - name: Preserve raw samples and environment + if: always() + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: search-performance-${{ github.run_id }} + path: build/search-performance/results + if-no-files-found: ignore + retention-days: 14 diff --git a/src/sx_core.c b/src/sx_core.c index a09638d..34e29af 100644 --- a/src/sx_core.c +++ b/src/sx_core.c @@ -281,6 +281,17 @@ extern void *memrchr(const void *s, int c, size_t n); #define SX_USE_MEMRCHR 0 #endif +/* Keep native substring search local to short forward-FIRST needles. + Long or repetitive needles retain KMP's linear worst-case bound. + The forced fallback is exercised by the sanitizer suite. */ +#if !defined(SX_FORCE_NO_MEMMEM) && defined(__GLIBC__) +extern void *memmem(const void *haystack, size_t haystacklen, + const void *needle, size_t needlelen); +#define SX_USE_MEMMEM 1 +#else +#define SX_USE_MEMMEM 0 +#endif + /* * Internal search primitive. Byte-exact (memcmp semantics) search for * needle[0 .. len) inside h's content region; an embedded '\0' in the @@ -296,7 +307,7 @@ extern void *memrchr(const void *s, int c, size_t n); * * opt bit1 (2): "first" -- single result: leftmost (or, with right, * rightmost) match position, or (find_ret_t)-1 if none. - * No allocation. + * KMP fallback may allocate a temporary prefix table. * opt bit1 clear: ALL mode -- malloc'd size_t array, caller frees: * arr[0] = count, arr[1..count] = positions in ascending order * (overlapping matches included). count == 0 -> a valid {0} array. @@ -381,7 +392,40 @@ static inline find_ret_t find(const sx_t *h, const char *needle, int len, return (find_ret_t)r; } - /* m >= 2 */ + if (first && !right) { + /* A front hit needs neither preprocessing nor an allocation. */ + if (memcmp(t + l, needle, m) == 0) + return (find_ret_t)l; + if (er - l == m) + return (find_ret_t)-1; + + /* Only [l+1, er-m] can start another legal window. memchr lets + libc scan these bytes in batches instead of advancing KMP one + byte at a time when the first byte is absent. */ + const char *p = memchr(t + l + 1, needle[0], er - m - l); + if (!p) + return (find_ret_t)-1; + l = (size_t)(p - t); + + /* No earlier window can match if its final byte is absent. This + also avoids KMP's fallback chain on a long repeated prefix. + The initial region check proves both lengths are in bounds. */ + p = memchr(t + l + m - 1, needle[m - 1], er - l - m + 1); + if (!p) + return (find_ret_t)-1; + l = (size_t)(p - t) - (m - 1); + +#if SX_USE_MEMMEM + /* A small private cutoff bounds preprocessing and avoids routing + long repeated-prefix needles through libc's short-pattern path. */ + if (m <= 32) { + p = memmem(t + l, er - l, needle, m); + return p ? (find_ret_t)(p - t) : (find_ret_t)-1; + } +#endif + } + + /* m >= 2: portable KMP fallback, reverse-FIRST and ALL modes */ size_t *pi = malloc(m * sizeof(*pi)); if (!pi) return first ? (find_ret_t)-1 : 0; diff --git a/tests/find_differential.c b/tests/find_differential.c new file mode 100644 index 0000000..56ea735 --- /dev/null +++ b/tests/find_differential.c @@ -0,0 +1,13 @@ +// Include include +// Include src +// Include /usr/lib/forge/include +// Source src/sx_raw.c +// Source src/sx_core.c +// Source src/sx_adv.c +// Option -std=c23 +// Option -O1 +// Option -g +// Option -fsanitize=address,undefined +// Option -fno-omit-frame-pointer +// Library /usr/local/lib +#include "find_differential.h" diff --git a/tests/find_differential.h b/tests/find_differential.h new file mode 100644 index 0000000..dcb2e98 --- /dev/null +++ b/tests/find_differential.h @@ -0,0 +1,124 @@ +#ifndef SX_FIND_DIFFERENTIAL_TEST +#define SX_FIND_DIFFERENTIAL_TEST +#include "sx_core.h" +#include +#include +#include + +/* Independent window-by-window oracle. Test binary content, nonzero + view offsets and boundaries at either side of legal match windows. + Both native and forced-portable builds execute the same cases. */ +static size_t reference(const unsigned char *h, size_t n, + const unsigned char *p, size_t m, size_t start) { + if (!m || start >= n || m > n - start) + return SIZE_MAX; + for (size_t i = start; i <= n - m; ++i) { + size_t j = 0; + while (j < m && h[i + j] == p[j]) + ++j; + if (j == m) + return i; + } + return SIZE_MAX; +} + +static uint32_t state = 0x72d9a351; +static uint32_t next(void) { + state ^= state << 13; + state ^= state >> 17; + state ^= state << 5; + return state; +} + +static void check(const unsigned char *h, size_t n, + const unsigned char *p, size_t m) { + /* Minimal capacities put the content terminator immediately before + the ASan redzone. The view's content also ends at its terminator. */ + sx_t *text = sx_new_with_cap(n + 1); + sx_t *pattern = sx_new_with_cap(m + 4); + TEST(text && pattern); + TEST(sx_truncate(text, n) == text); + TEST(sx_truncate(pattern, m + 3) == pattern); + memcpy(sx_buf_mut(text), h, n); + memset(sx_buf_mut(pattern), 0xa5, 3); + memcpy(sx_buf_mut(pattern) + 3, p, m); + sx_view_t v = sx_view(pattern); + v.offset = 3; + v.len = m; + + size_t expected = reference(h, n, p, m, 0); + TEST(sx_find_view(text, v) == expected); + sx_t *owned_pattern = sx_new_from_view(v); + TEST(owned_pattern); + TEST(sx_find(text, owned_pattern) == expected); + if (!memchr(p, 0, m)) + TEST(sx_find_cstr(text, sx_buf_mut(owned_pattern)) == expected); + + size_t bounds[] = {0, 1, n / 2, n, n + 1, SIZE_MAX, + n >= m ? n - m : 0, next() % (n + 1)}; + for (size_t i = 0; i < sizeof(bounds) / sizeof(bounds[0]); ++i) + TEST(sx_find_view_b(text, v, bounds[i]) == + reference(h, n, p, m, bounds[i])); + if (expected != SIZE_MAX) { + TEST(sx_find_view_b(text, v, expected) == expected); + TEST(sx_find_view_b(text, v, expected + 1) == + reference(h, n, p, m, expected + 1)); + } + sx_free(owned_pattern); + sx_free(pattern); + sx_free(text); +} + +int main(void) { + unsigned char h[2048], p[320]; + const size_t lengths[] = {0, 1, 2, 3, 7, 8, 16, 31, 32, 33, + 63, 64, 127, 128, 129, 255, 256, 257, 320}; + for (size_t k = 0; k < sizeof(lengths) / sizeof(lengths[0]); ++k) { + size_t m = lengths[k]; + for (size_t n = 0; n <= m + 2; ++n) { + memset(h, 'a', n); + memset(p, 'a', m); + check(h, n, p, m); + if (m) { + p[m - 1] = 'b'; + check(h, n, p, m); + } + } + for (unsigned mode = 0; mode < 6; ++mode) { + memset(h, 'a', sizeof(h)); + memset(p, 'a', m); + if (m) + p[m - 1] = 'b'; + if (mode == 1 && m) /* tail hit */ + memcpy(h + sizeof(h) - m, p, m); + if (mode == 2 && m) /* middle hit */ + memcpy(h + sizeof(h) / 2, p, m); + if (mode == 3) /* both endpoint bytes present; near matches */ + for (size_t i = 0; i < sizeof(h); ++i) + h[i] = (i % (m + 1) == 0) ? 'b' : 'a'; + if (mode == 4) /* binary content, high bytes and NULs */ + for (size_t i = 0; i < m; ++i) + p[i] = (unsigned char)(i * 113); + if (mode == 5 && m) { + memset(p, 'a', m); + p[m / 2] = 'c'; /* equal endpoints do not imply a match */ + h[sizeof(h) / 2] = 'c'; + } + check(h, sizeof(h), p, m); + } + } + for (unsigned it = 0; it < 3000; ++it) { + size_t n = next() % (sizeof(h) + 1); + size_t m = next() % (sizeof(p) + 1); + unsigned alphabet = it % 3 == 0 ? 256 : it % 3 == 1 ? 3 : 1; + for (size_t i = 0; i < n; ++i) + h[i] = (unsigned char)(next() % alphabet); + for (size_t i = 0; i < m; ++i) + p[i] = (unsigned char)(next() % alphabet); + if (m && m <= n && it % 2 == 0) + memcpy(h + next() % (n - m + 1), p, m); + check(h, n, p, m); + } + PASS(); +} +#endif diff --git a/tests/find_differential_fallback.c b/tests/find_differential_fallback.c new file mode 100644 index 0000000..c3cc83a --- /dev/null +++ b/tests/find_differential_fallback.c @@ -0,0 +1,14 @@ +// Include include +// Include src +// Include /usr/lib/forge/include +// Source src/sx_raw.c +// Source src/sx_core.c +// Source src/sx_adv.c +// Option -std=c23 +// Option -O1 +// Option -g +// Option -fsanitize=address,undefined +// Option -fno-omit-frame-pointer +// Option -DSX_FORCE_NO_MEMMEM +// Library /usr/local/lib +#include "find_differential.h" From 9a37b85064774d934e9807699ff438c53797177f Mon Sep 17 00:00:00 2001 From: minelogy <72928567+minelogy-dev@users.noreply.github.com> Date: Sun, 1 Nov 2026 08:02:43 -0800 Subject: [PATCH 02/10] perf: skip noncandidate bytes when forward KMP resets Use memchr only when the prefix state has fallen back to zero, preserving linear scanning and the existing all-match behavior. Co-authored-by: Codex --- src/sx_core.c | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/src/sx_core.c b/src/sx_core.c index 34e29af..fa7bc1a 100644 --- a/src/sx_core.c +++ b/src/sx_core.c @@ -487,6 +487,18 @@ static inline find_ret_t find(const sx_t *h, const char *needle, int len, q = pi[q - 1]; if (t[i] == needle[q]) q++; + else if (first) { + /* A mismatch after all fallbacks leaves q == 0. Skip bytes + that cannot start a match, then consume the first byte of + the next candidate. These disjoint scans keep KMP linear. */ + const char *p = memchr(t + i + 1, needle[0], er - i - 1); + if (!p) { + free(pi); + return (find_ret_t)-1; + } + i = (size_t)(p - t); + q = 1; + } if (q == m) { size_t pos = i + 1 - m; if (first) { From fea8948fc5f47fe12052e5e298aad6fd89be7494 Mon Sep 17 00:00:00 2001 From: minelogy <72928567+minelogy-dev@users.noreply.github.com> Date: Sun, 1 Nov 2026 08:06:03 -0800 Subject: [PATCH 03/10] perf: consume dense KMP candidates without a libc call Compare the portable search build alongside native before/after results. Co-authored-by: Codex --- .github/scripts/compare-search.py | 19 +++++++++++++------ src/sx_core.c | 14 +++++++++----- 2 files changed, 22 insertions(+), 11 deletions(-) diff --git a/.github/scripts/compare-search.py b/.github/scripts/compare-search.py index 304af56..88cd3e6 100644 --- a/.github/scripts/compare-search.py +++ b/.github/scripts/compare-search.py @@ -78,6 +78,7 @@ def main(): "pinned_cpu": cpu, "lscpu": json.loads(bench.output(["lscpu", "-J"])), "libc": bench.output(["ldd", "--version"]).splitlines()[0], "timing_flags": bench.COMMON + ["-O3", "-DNDEBUG"], + "portable_flags": ["-DSX_FORCE_NO_MEMMEM"], "samples": 11, "target_sample_ns": 20000000, "note": "Variants run sequentially on the same pinned CPU. Hosted-runner scheduling and frequency remain uncontrolled.", } @@ -90,10 +91,12 @@ def main(): env = os.environ.copy() env.update(ASAN_OPTIONS="detect_leaks=1:halt_on_error=1", UBSAN_OPTIONS="halt_on_error=1:print_stacktrace=1") + common_flags = list(bench.COMMON) for ci, cc in enumerate(("gcc-14", "clang-19")): results = {} - for variant in (("before", "after") if ci == 0 else ("after", "before")): - bench.ROOT = WORK / variant + for variant in (("before", "after", "portable") if ci == 0 else ("portable", "after", "before")): + bench.ROOT = WORK / ("before" if variant == "before" else "after") + bench.COMMON = common_flags + (["-DSX_FORCE_NO_MEMMEM"] if variant == "portable" else []) folder = out / cc / variant folder.mkdir(parents=True, exist_ok=True) log = folder / "commands.log" @@ -121,9 +124,10 @@ def main(): } (folder / "summary.json").write_text(json.dumps(list(stats.values()), indent=2) + "\n") results[variant] = stats + bench.COMMON = common_flags report += [f"## {bench.output([cc, '--version']).splitlines()[0]}", "", - "| Case | Before ns | After ns | Before/after | After malloc calls |", - "| --- | ---: | ---: | ---: | ---: |"] + "| Case | Before ns | Native ns | Portable ns | Native speedup | Portable speedup |", + "| --- | ---: | ---: | ---: | ---: | ---: |"] compared = [] for key, before in sorted(results["before"].items()): case, library = key @@ -131,9 +135,12 @@ def main(): continue after_row = results["after"][key] ratio = before["median_ns"] / after_row["median_ns"] - row = {"case": case, "before": before, "after": after_row, "speedup": ratio} + portable = results["portable"][key] + portable_ratio = before["median_ns"] / portable["median_ns"] + row = {"case": case, "before": before, "after": after_row, "speedup": ratio, + "portable": portable, "portable_speedup": portable_ratio} compared.append(row) - report.append(f"| {case} | {before['median_ns']:.2f} | {after_row['median_ns']:.2f} | {ratio:.2f}x | {after_row['malloc_calls']} |") + report.append(f"| {case} | {before['median_ns']:.2f} | {after_row['median_ns']:.2f} | {portable['median_ns']:.2f} | {ratio:.2f}x | {portable_ratio:.2f}x |") print("SEARCH_COMPARE_JSON=" + json.dumps({"compiler": cc, "results": compared}), flush=True) report.append("") text = "\n".join(report) + "\n" diff --git a/src/sx_core.c b/src/sx_core.c index fa7bc1a..176dcd6 100644 --- a/src/sx_core.c +++ b/src/sx_core.c @@ -491,12 +491,16 @@ static inline find_ret_t find(const sx_t *h, const char *needle, int len, /* A mismatch after all fallbacks leaves q == 0. Skip bytes that cannot start a match, then consume the first byte of the next candidate. These disjoint scans keep KMP linear. */ - const char *p = memchr(t + i + 1, needle[0], er - i - 1); - if (!p) { - free(pi); - return (find_ret_t)-1; + if (++i == er) + break; + /* Dense candidates need no libc call (for example "abab..."). + Otherwise let memchr skip the remaining unrelated bytes. */ + if (t[i] != needle[0]) { + const char *p = memchr(t + i + 1, needle[0], er - i - 1); + if (!p) + break; + i = (size_t)(p - t); } - i = (size_t)(p - t); q = 1; } if (q == m) { From b097ae0cf9527b739e10cb202bc34e14aa6ddd04 Mon Sep 17 00:00:00 2001 From: minelogy <72928567+minelogy-dev@users.noreply.github.com> Date: Sun, 1 Nov 2026 08:16:39 -0800 Subject: [PATCH 04/10] perf: retain scalar KMP for dense forward candidates Stop batch skipping after eight nearby candidates and resume scalar KMP at the first unconsumed candidate. This bounds setup work on periodic inputs and keeps sparse-candidate acceleration portable. Co-authored-by: Codex --- src/sx_core.c | 62 ++++++++++++++++++++++++++++++++++++++------------- 1 file changed, 46 insertions(+), 16 deletions(-) diff --git a/src/sx_core.c b/src/sx_core.c index 176dcd6..ed64551 100644 --- a/src/sx_core.c +++ b/src/sx_core.c @@ -471,6 +471,52 @@ static inline find_ret_t find(const sx_t *h, const char *needle, int len, pi[i] = k; } + if (first) { + /* Batch skipping helps sparse candidates. After eight consecutive + skips of fewer than eight bytes, resume the scalar KMP below. + Dense/periodic inputs then pay only bounded setup work. */ + unsigned near_budget = 8; + size_t q = 0, i = l; + for (; i < er; i++) { + while (q && t[i] != needle[q]) + q = pi[q - 1]; + if (t[i] == needle[q]) + q++; + else { + /* All fallbacks failed: q == 0, so only a new start can match. */ + if (++i == er) + break; + size_t next = i; + if (t[i] != needle[0]) { + const char *p = memchr(t + i + 1, needle[0], er - i - 1); + if (!p) { + free(pi); + return (find_ret_t)-1; + } + next = (size_t)(p - t); + } + if (next - i < 8) { + if (--near_budget == 0) { + l = next; /* this candidate has not been consumed */ + break; + } + } else { + near_budget = 8; + } + i = next; + q = 1; + } + if (q == m) { + free(pi); + return (find_ret_t)(i + 1 - m); + } + } + if (i == er) { + free(pi); + return (find_ret_t)-1; + } + } + size_t *r = NULL; size_t cap = 0, cnt = 0; if (!first) { @@ -487,22 +533,6 @@ static inline find_ret_t find(const sx_t *h, const char *needle, int len, q = pi[q - 1]; if (t[i] == needle[q]) q++; - else if (first) { - /* A mismatch after all fallbacks leaves q == 0. Skip bytes - that cannot start a match, then consume the first byte of - the next candidate. These disjoint scans keep KMP linear. */ - if (++i == er) - break; - /* Dense candidates need no libc call (for example "abab..."). - Otherwise let memchr skip the remaining unrelated bytes. */ - if (t[i] != needle[0]) { - const char *p = memchr(t + i + 1, needle[0], er - i - 1); - if (!p) - break; - i = (size_t)(p - t); - } - q = 1; - } if (q == m) { size_t pos = i + 1 - m; if (first) { From f8db20ed356af89606bd813297ec64b8d94dafb1 Mon Sep 17 00:00:00 2001 From: minelogy <72928567+minelogy-dev@users.noreply.github.com> Date: Sun, 1 Nov 2026 08:25:44 -0800 Subject: [PATCH 05/10] perf: isolate native fast paths and preserve portable KMP Keep the original KMP kernel unchanged. Apply front-window and endpoint filters in a glibc-only forward-search adapter, using native memmem for short patterns. Focus final measurements on the sixteen search cases, including the forced-portable build. Co-authored-by: Codex --- .github/scripts/compare-search.py | 7 +- src/sx_core.c | 159 ++++++++++++------------------ 2 files changed, 69 insertions(+), 97 deletions(-) diff --git a/.github/scripts/compare-search.py b/.github/scripts/compare-search.py index 88cd3e6..fe21481 100644 --- a/.github/scripts/compare-search.py +++ b/.github/scripts/compare-search.py @@ -64,6 +64,11 @@ def main(): } """ source = source.replace(anchor, setup + anchor, 1) + anchor = " Fixture f; prepare(&f, &cases[ci]);" + assert anchor in source + source = source.replace(anchor, + " if (cases[ci].op != FIND && cases[ci].op != FIND_CHAR) continue;\\n" + + anchor, 1) for variant in ("before", "after"): folder = WORK / variant / "benchmarks" folder.mkdir(parents=True, exist_ok=True) @@ -112,7 +117,7 @@ def main(): groups = {} for r in rows: groups.setdefault((r["case"], r["library"]), []).append(float(r["ns_per_op"])) - assert len(groups) == 82 + len(extra) * 3, len(groups) + assert len(groups) == (8 + len(extra)) * 3, len(groups) stats = {} for (case, library), values in groups.items(): assert len(values) == 11 diff --git a/src/sx_core.c b/src/sx_core.c index ed64551..a36a405 100644 --- a/src/sx_core.c +++ b/src/sx_core.c @@ -281,17 +281,6 @@ extern void *memrchr(const void *s, int c, size_t n); #define SX_USE_MEMRCHR 0 #endif -/* Keep native substring search local to short forward-FIRST needles. - Long or repetitive needles retain KMP's linear worst-case bound. - The forced fallback is exercised by the sanitizer suite. */ -#if !defined(SX_FORCE_NO_MEMMEM) && defined(__GLIBC__) -extern void *memmem(const void *haystack, size_t haystacklen, - const void *needle, size_t needlelen); -#define SX_USE_MEMMEM 1 -#else -#define SX_USE_MEMMEM 0 -#endif - /* * Internal search primitive. Byte-exact (memcmp semantics) search for * needle[0 .. len) inside h's content region; an embedded '\0' in the @@ -392,40 +381,7 @@ static inline find_ret_t find(const sx_t *h, const char *needle, int len, return (find_ret_t)r; } - if (first && !right) { - /* A front hit needs neither preprocessing nor an allocation. */ - if (memcmp(t + l, needle, m) == 0) - return (find_ret_t)l; - if (er - l == m) - return (find_ret_t)-1; - - /* Only [l+1, er-m] can start another legal window. memchr lets - libc scan these bytes in batches instead of advancing KMP one - byte at a time when the first byte is absent. */ - const char *p = memchr(t + l + 1, needle[0], er - m - l); - if (!p) - return (find_ret_t)-1; - l = (size_t)(p - t); - - /* No earlier window can match if its final byte is absent. This - also avoids KMP's fallback chain on a long repeated prefix. - The initial region check proves both lengths are in bounds. */ - p = memchr(t + l + m - 1, needle[m - 1], er - l - m + 1); - if (!p) - return (find_ret_t)-1; - l = (size_t)(p - t) - (m - 1); - -#if SX_USE_MEMMEM - /* A small private cutoff bounds preprocessing and avoids routing - long repeated-prefix needles through libc's short-pattern path. */ - if (m <= 32) { - p = memmem(t + l, er - l, needle, m); - return p ? (find_ret_t)(p - t) : (find_ret_t)-1; - } -#endif - } - - /* m >= 2: portable KMP fallback, reverse-FIRST and ALL modes */ + /* m >= 2 */ size_t *pi = malloc(m * sizeof(*pi)); if (!pi) return first ? (find_ret_t)-1 : 0; @@ -471,52 +427,6 @@ static inline find_ret_t find(const sx_t *h, const char *needle, int len, pi[i] = k; } - if (first) { - /* Batch skipping helps sparse candidates. After eight consecutive - skips of fewer than eight bytes, resume the scalar KMP below. - Dense/periodic inputs then pay only bounded setup work. */ - unsigned near_budget = 8; - size_t q = 0, i = l; - for (; i < er; i++) { - while (q && t[i] != needle[q]) - q = pi[q - 1]; - if (t[i] == needle[q]) - q++; - else { - /* All fallbacks failed: q == 0, so only a new start can match. */ - if (++i == er) - break; - size_t next = i; - if (t[i] != needle[0]) { - const char *p = memchr(t + i + 1, needle[0], er - i - 1); - if (!p) { - free(pi); - return (find_ret_t)-1; - } - next = (size_t)(p - t); - } - if (next - i < 8) { - if (--near_budget == 0) { - l = next; /* this candidate has not been consumed */ - break; - } - } else { - near_budget = 8; - } - i = next; - q = 1; - } - if (q == m) { - free(pi); - return (find_ret_t)(i + 1 - m); - } - } - if (i == er) { - free(pi); - return (find_ret_t)-1; - } - } - size_t *r = NULL; size_t cap = 0, cnt = 0; if (!first) { @@ -567,6 +477,63 @@ static inline find_ret_t find(const sx_t *h, const char *needle, int len, r[0] = cnt; return (find_ret_t)r; } +/* Native forward search is isolated from the portable KMP kernel so + its additional control flow does not perturb the fallback loop. + -DSX_FORCE_NO_MEMMEM exercises the original portable implementation. */ +#if !defined(SX_FORCE_NO_MEMMEM) && defined(__GLIBC__) +extern void *memmem(const void *haystack, size_t haystacklen, + const void *needle, size_t needlelen); +#define SX_USE_MEMMEM 1 +#else +#define SX_USE_MEMMEM 0 +#endif + +static inline find_ret_t find_first(const sx_t *h, const char *needle, int len, + size_t boundary) { +#if SX_USE_MEMMEM + const size_t H = h->ref->len; + const size_t m = (size_t)len; + const char *t = h->ref->ptr; + size_t l = boundary; + if (len <= 0 || l >= H || m > H - l) + return (find_ret_t)-1; + if (m == 1) { + const char *p = memchr(t + l, needle[0], H - l); + return p ? (find_ret_t)(p - t) : (find_ret_t)-1; + } + + /* Front hits need no preprocessing or prefix-table allocation. */ + if (memcmp(t + l, needle, m) == 0) + return (find_ret_t)l; + if (H - l == m) + return (find_ret_t)-1; + + /* Only [l+1, H-m] can start another legal window. */ + const char *p = memchr(t + l + 1, needle[0], H - m - l); + if (!p) + return (find_ret_t)-1; + l = (size_t)(p - t); + + /* A valid window must also end with the needle's final byte. + No earlier start can match before this first possible endpoint. */ + p = memchr(t + l + m - 1, needle[m - 1], H - l - m + 1); + if (!p) + return (find_ret_t)-1; + l = (size_t)(p - t) - (m - 1); + + /* Keep native search local to short patterns. Long repeated prefixes + can be a bad case for libc's short-pattern implementation; KMP + retains the linear bound for arbitrary long needles. */ + if (m <= 32) { + p = memmem(t + l, H - l, needle, m); + return p ? (find_ret_t)(p - t) : (find_ret_t)-1; + } + return find(h, needle, len, l, 2); +#else + return find(h, needle, len, boundary, 2); +#endif +} + /* Wrappers translate the public API onto find(). Per the buffer model, a needle's searchable length is its CONTENT length (the trailing '\0' at ptr[len] is not content): sx_find* pass the needle's own length, @@ -575,7 +542,7 @@ static inline find_ret_t find(const sx_t *h, const char *needle, int len, SYMBOL_PUBLIC size_t sx_find(const sx_t *h, const sx_t *needle) { if (!h || !needle) return (size_t)-1; - return (size_t)find(h, needle->ref->ptr, needle->ref->len, 0, 2); + return (size_t)find_first(h, needle->ref->ptr, needle->ref->len, 0); } SYMBOL_PUBLIC size_t sx_find_view(const sx_t *h, sx_view_t needle) { return sx_find_view_b(h, needle, 0); @@ -585,18 +552,18 @@ SYMBOL_PUBLIC size_t sx_find_view_b(const sx_t *h, sx_view_t needle, size_t boundary) { if (!h) return (size_t)-1; - return (size_t)find(h, needle.ref->ptr + needle.offset, needle.len, boundary, - 2); + return (size_t)find_first(h, needle.ref->ptr + needle.offset, needle.len, + boundary); } SYMBOL_PUBLIC size_t sx_find_cstr(const sx_t *h, const char *needle) { if (!h || !needle) return (size_t)-1; - return (size_t)find(h, needle, (int)strlen(needle), 0, 2); + return (size_t)find_first(h, needle, (int)strlen(needle), 0); } SYMBOL_PUBLIC size_t sx_find_char(const sx_t *h, char c) { if (!h) return (size_t)-1; - return (size_t)find(h, &c, 1, 0, 2); + return (size_t)find_first(h, &c, 1, 0); } SYMBOL_PUBLIC size_t sx_rfind(const sx_t *h, const sx_t *needle) { if (!h || !needle) From e3f17f356bd84b9b4cb5cf9da83d92abc87233f4 Mon Sep 17 00:00:00 2001 From: minelogy <72928567+minelogy-dev@users.noreply.github.com> Date: Sun, 1 Nov 2026 08:26:16 -0800 Subject: [PATCH 06/10] test: preserve source newlines when selecting search cases Co-authored-by: Codex --- .github/scripts/compare-search.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/scripts/compare-search.py b/.github/scripts/compare-search.py index fe21481..c831c09 100644 --- a/.github/scripts/compare-search.py +++ b/.github/scripts/compare-search.py @@ -67,8 +67,8 @@ def main(): anchor = " Fixture f; prepare(&f, &cases[ci]);" assert anchor in source source = source.replace(anchor, - " if (cases[ci].op != FIND && cases[ci].op != FIND_CHAR) continue;\\n" - + anchor, 1) + " if (cases[ci].op != FIND && cases[ci].op != FIND_CHAR) continue;" + + chr(10) + anchor, 1) for variant in ("before", "after"): folder = WORK / variant / "benchmarks" folder.mkdir(parents=True, exist_ok=True) From 2341a503124dbcfc338e0bfeac1598a350598b75 Mon Sep 17 00:00:00 2001 From: minelogy <72928567+minelogy-dev@users.noreply.github.com> Date: Sun, 1 Nov 2026 08:27:21 -0800 Subject: [PATCH 07/10] test: derive benchmark group count from selected search cases Co-authored-by: Codex --- .github/scripts/compare-search.py | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/.github/scripts/compare-search.py b/.github/scripts/compare-search.py index c831c09..df6e5d2 100644 --- a/.github/scripts/compare-search.py +++ b/.github/scripts/compare-search.py @@ -69,6 +69,9 @@ def main(): source = source.replace(anchor, " if (cases[ci].op != FIND && cases[ci].op != FIND_CHAR) continue;" + chr(10) + anchor, 1) + search_cases = sum(1 for line in source.splitlines() + if line.lstrip().startswith('{"') + and (", FIND," in line or ", FIND_CHAR," in line)) for variant in ("before", "after"): folder = WORK / variant / "benchmarks" folder.mkdir(parents=True, exist_ok=True) @@ -84,6 +87,7 @@ def main(): "libc": bench.output(["ldd", "--version"]).splitlines()[0], "timing_flags": bench.COMMON + ["-O3", "-DNDEBUG"], "portable_flags": ["-DSX_FORCE_NO_MEMMEM"], + "cases": search_cases, "samples": 11, "target_sample_ns": 20000000, "note": "Variants run sequentially on the same pinned CPU. Hosted-runner scheduling and frequency remain uncontrolled.", } @@ -117,7 +121,7 @@ def main(): groups = {} for r in rows: groups.setdefault((r["case"], r["library"]), []).append(float(r["ns_per_op"])) - assert len(groups) == (8 + len(extra)) * 3, len(groups) + assert len(groups) == search_cases * 3, len(groups) stats = {} for (case, library), values in groups.items(): assert len(values) == 11 From 04060567d3d914a3483a7c2152b6102e910ac05b Mon Sep 17 00:00:00 2001 From: minelogy <72928567+minelogy-dev@users.noreply.github.com> Date: Sun, 1 Nov 2026 08:32:52 -0800 Subject: [PATCH 08/10] perf: preserve the original KMP entry for long needles Endpoint checks can reject a missing long needle without allocation. If both endpoints exist, enter KMP with the original boundary so the fallback retains its existing compiler specialization. Co-authored-by: Codex --- src/sx_core.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/sx_core.c b/src/sx_core.c index a36a405..841d865 100644 --- a/src/sx_core.c +++ b/src/sx_core.c @@ -528,7 +528,9 @@ static inline find_ret_t find_first(const sx_t *h, const char *needle, int len, p = memmem(t + l, H - l, needle, m); return p ? (find_ret_t)(p - t) : (find_ret_t)-1; } - return find(h, needle, len, l, 2); + /* Preserve the original KMP entry and compiler specialization when + the endpoint checks cannot reject a long needle. */ + return find(h, needle, len, boundary, 2); #else return find(h, needle, len, boundary, 2); #endif From 37b1bd48aac0358d7891da6f76face9ea20050f7 Mon Sep 17 00:00:00 2001 From: minelogy <72928567+minelogy-dev@users.noreply.github.com> Date: Sun, 1 Nov 2026 08:40:36 -0800 Subject: [PATCH 09/10] perf: isolate native checks from KMP compiler specialization Keep the optional native decision in a non-inlined private function and retain the original KMP call context. Measure six representative search cases across three fresh processes per compiler and variant; sanitizer validation continues to cover all fifteen search cases. Co-authored-by: Codex --- .github/scripts/compare-search.py | 28 ++++++++++---- src/sx_core.c | 61 ++++++++++++++++++------------- 2 files changed, 56 insertions(+), 33 deletions(-) diff --git a/.github/scripts/compare-search.py b/.github/scripts/compare-search.py index df6e5d2..d0cc7f4 100644 --- a/.github/scripts/compare-search.py +++ b/.github/scripts/compare-search.py @@ -72,6 +72,17 @@ def main(): search_cases = sum(1 for line in source.splitlines() if line.lstrip().startswith('{"') and (", FIND," in line or ", FIND_CHAR," in line)) + timing_names = [ + "find8_miss_65536", "find128_repeated_miss_65536", + "common8_miss_65536", "common33_miss_65536", + "periodic8_miss_65536", "repeated128_end_present_miss_65536", + ] + selected = " || ".join(f'strcmp(cases[ci].name, "{name}") == 0' + for name in timing_names) + source = source.replace(anchor, + f" if (!check_only && !({selected})) continue;" + + chr(10) + anchor, 1) + repeats = 3 for variant in ("before", "after"): folder = WORK / variant / "benchmarks" folder.mkdir(parents=True, exist_ok=True) @@ -87,15 +98,15 @@ def main(): "libc": bench.output(["ldd", "--version"]).splitlines()[0], "timing_flags": bench.COMMON + ["-O3", "-DNDEBUG"], "portable_flags": ["-DSX_FORCE_NO_MEMMEM"], - "cases": search_cases, - "samples": 11, "target_sample_ns": 20000000, + "correctness_cases": search_cases, "timing_cases": len(timing_names), + "processes": repeats, "samples_per_process": 11, "samples": 11 * repeats, "target_sample_ns": 20000000, "note": "Variants run sequentially on the same pinned CPU. Hosted-runner scheduling and frequency remain uncontrolled.", } (out / "environment.json").write_text(json.dumps(metadata, indent=2) + "\n") (out / "strings.c").write_text(source) print("SEARCH_COMPARE_ENV=" + json.dumps(metadata), flush=True) report = ["# Search before/after", "", - "Same job, pinned CPU, -O3, no LTO; medians of 11 hot-input samples.", + "Same job, pinned CPU, -O3, no LTO; 3 fresh processes, 11 hot-input samples each.", "Sequential runs are subject to host scheduling/frequency changes; small differences are inconclusive.", ""] env = os.environ.copy() env.update(ASAN_OPTIONS="detect_leaks=1:halt_on_error=1", @@ -112,19 +123,22 @@ def main(): check = bench.compile_binary(cc, folder / "check", "check", deps, log) bench.invoke([str(check), "--check"], log, env=env, cpu=cpu) binary = bench.compile_binary(cc, folder / "timing", "timing", deps, log) - bench.invoke([str(binary)], log, stdout=folder / "samples.csv", cpu=cpu) + rows = [] + for process in range(repeats): + samples = folder / f"samples-{process}.csv" + bench.invoke([str(binary)], log, stdout=samples, cpu=cpu) + rows.extend(csv.DictReader(samples.open())) alloc = bench.compile_binary(cc, folder / "alloc", "alloc", deps, log) bench.invoke([str(alloc)], log, stdout=folder / "allocations.csv", cpu=cpu) - rows = list(csv.DictReader((folder / "samples.csv").open())) memory = {(r["case"], r["library"]): r for r in csv.DictReader((folder / "allocations.csv").open())} groups = {} for r in rows: groups.setdefault((r["case"], r["library"]), []).append(float(r["ns_per_op"])) - assert len(groups) == search_cases * 3, len(groups) + assert len(groups) == len(timing_names) * 3, len(groups) stats = {} for (case, library), values in groups.items(): - assert len(values) == 11 + assert len(values) == 11 * repeats stats[case, library] = { "case": case, "library": library, "median_ns": statistics.median(values), diff --git a/src/sx_core.c b/src/sx_core.c index 841d865..aeb1bd5 100644 --- a/src/sx_core.c +++ b/src/sx_core.c @@ -477,63 +477,72 @@ static inline find_ret_t find(const sx_t *h, const char *needle, int len, r[0] = cnt; return (find_ret_t)r; } -/* Native forward search is isolated from the portable KMP kernel so - its additional control flow does not perturb the fallback loop. - -DSX_FORCE_NO_MEMMEM exercises the original portable implementation. */ +/* Keep optional native checks out of the portable KMP callers' + optimizer context. The forced build uses the original path directly. */ #if !defined(SX_FORCE_NO_MEMMEM) && defined(__GLIBC__) extern void *memmem(const void *haystack, size_t haystacklen, const void *needle, size_t needlelen); -#define SX_USE_MEMMEM 1 -#else -#define SX_USE_MEMMEM 0 -#endif -static inline find_ret_t find_first(const sx_t *h, const char *needle, int len, - size_t boundary) { -#if SX_USE_MEMMEM +/* GCC and Clang support this private hint on glibc targets. It keeps + native-path conditions from changing the fallback's specialization. */ +static __attribute__((noinline)) int +try_native_find_first(const sx_t *h, const char *needle, int len, + size_t boundary, find_ret_t *result) { const size_t H = h->ref->len; const size_t m = (size_t)len; const char *t = h->ref->ptr; size_t l = boundary; + *result = (find_ret_t)-1; if (len <= 0 || l >= H || m > H - l) - return (find_ret_t)-1; + return 1; if (m == 1) { const char *p = memchr(t + l, needle[0], H - l); - return p ? (find_ret_t)(p - t) : (find_ret_t)-1; + if (p) + *result = (find_ret_t)(p - t); + return 1; } /* Front hits need no preprocessing or prefix-table allocation. */ - if (memcmp(t + l, needle, m) == 0) - return (find_ret_t)l; + if (memcmp(t + l, needle, m) == 0) { + *result = (find_ret_t)l; + return 1; + } if (H - l == m) - return (find_ret_t)-1; + return 1; /* Only [l+1, H-m] can start another legal window. */ const char *p = memchr(t + l + 1, needle[0], H - m - l); if (!p) - return (find_ret_t)-1; + return 1; l = (size_t)(p - t); /* A valid window must also end with the needle's final byte. No earlier start can match before this first possible endpoint. */ p = memchr(t + l + m - 1, needle[m - 1], H - l - m + 1); if (!p) - return (find_ret_t)-1; + return 1; l = (size_t)(p - t) - (m - 1); - /* Keep native search local to short patterns. Long repeated prefixes - can be a bad case for libc's short-pattern implementation; KMP - retains the linear bound for arbitrary long needles. */ + /* Limit native search to short patterns. Long repeated prefixes can + be a bad case for libc's short-pattern implementation. */ if (m <= 32) { p = memmem(t + l, H - l, needle, m); - return p ? (find_ret_t)(p - t) : (find_ret_t)-1; + if (p) + *result = (find_ret_t)(p - t); + return 1; } - /* Preserve the original KMP entry and compiler specialization when - the endpoint checks cannot reject a long needle. */ - return find(h, needle, len, boundary, 2); -#else - return find(h, needle, len, boundary, 2); + return 0; /* original KMP handles the unresolved long needle */ +} #endif + +static inline find_ret_t find_first(const sx_t *h, const char *needle, int len, + size_t boundary) { +#if !defined(SX_FORCE_NO_MEMMEM) && defined(__GLIBC__) + find_ret_t result; + if (try_native_find_first(h, needle, len, boundary, &result)) + return result; +#endif + return find(h, needle, len, boundary, 2); } /* Wrappers translate the public API onto find(). Per the buffer model, From 40987da6ddaa2f31ca04d5d7f4545fa0704b7eb4 Mon Sep 17 00:00:00 2001 From: minelogy <72928567+minelogy-dev@users.noreply.github.com> Date: Sun, 1 Nov 2026 08:42:14 -0800 Subject: [PATCH 10/10] perf: preserve the direct single-byte search path Keep sx_find_char on its original memchr specialization and include it in the repeated-process performance comparison. Co-authored-by: Codex --- .github/scripts/compare-search.py | 1 + src/sx_core.c | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/.github/scripts/compare-search.py b/.github/scripts/compare-search.py index d0cc7f4..2249818 100644 --- a/.github/scripts/compare-search.py +++ b/.github/scripts/compare-search.py @@ -74,6 +74,7 @@ def main(): and (", FIND," in line or ", FIND_CHAR," in line)) timing_names = [ "find8_miss_65536", "find128_repeated_miss_65536", + "find_char_end_65536", "common8_miss_65536", "common33_miss_65536", "periodic8_miss_65536", "repeated128_end_present_miss_65536", ] diff --git a/src/sx_core.c b/src/sx_core.c index aeb1bd5..43adca9 100644 --- a/src/sx_core.c +++ b/src/sx_core.c @@ -574,7 +574,7 @@ SYMBOL_PUBLIC size_t sx_find_cstr(const sx_t *h, const char *needle) { SYMBOL_PUBLIC size_t sx_find_char(const sx_t *h, char c) { if (!h) return (size_t)-1; - return (size_t)find_first(h, &c, 1, 0); + return (size_t)find(h, &c, 1, 0, 2); } SYMBOL_PUBLIC size_t sx_rfind(const sx_t *h, const sx_t *needle) { if (!h || !needle)