Skip to content

perf: cache compiled CRD regex + skip hex-preview Vec allocation#40

Open
indyjonesnl wants to merge 2 commits into
calfonso:mainfrom
indyjonesnl:upstream/perf-regex-cache
Open

perf: cache compiled CRD regex + skip hex-preview Vec allocation#40
indyjonesnl wants to merge 2 commits into
calfonso:mainfrom
indyjonesnl:upstream/perf-regex-cache

Conversation

@indyjonesnl
Copy link
Copy Markdown

Changes

Two unrelated perf wins, kept together because both are small and obviously safe.

`perf(schema-validation): cache compiled regex patterns`

`SchemaValidator::validate_string` recompiled `regex::Regex::new(pattern)` on every CRD field that declared a `pattern`. On a busy admission webhook this is a measurable hot path — regex compile dominates the validation cost.

Cache compiled patterns in a process-wide `LazyLock<RwLock<HashMap<String, Regex>>>`. Read-lock for the common hit path; write-lock only on miss. Bad regexes still return `InvalidResource` errors and are not cached.

Includes a microbenchmark (`#[ignore]`, run with `--release --ignored`) that compares the cached path against `Regex::new` per call:

```
regex_cache_speedup: n=5000 cached=3.59ms uncached=259.39ms speedup=72.3x
```

`perf(middleware): build hex body preview directly into String`

Protobuf debug-logging path used `.map(|b| format!("{:02x}", b)).collect::<Vec<_>>().join(" ")`, allocating an intermediate `Vec` of 80 entries on every protobuf request. Write directly into a pre-allocated `String` via `write!` — same output, one allocation instead of 81.

Verification

`cargo build --workspace --locked` clean. Two new tests on the regex cache (correctness + the ignored bench) pass. No new test failures vs baseline.

Depends on #32 for green CI.

indyjonesnl and others added 2 commits May 14, 2026 17:49
validate_string recompiled regex::Regex::new(pattern) on every CRD
field that declared a pattern. Cache compiled patterns in a process-wide
LazyLock<RwLock<HashMap<String, Regex>>>; bad patterns are still
returned as InvalidResource errors and are not cached.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Avoids the intermediate Vec<String> from collect()+join() in the
protobuf debug-logging path.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant