| 1 | # cert.rs Performance Improvement Plan |
| 2 | |
| 3 | ## Problem |
| 4 | |
| 5 | Our changes in `19dd2c187` ("specific der types") introduced a ~2x performance |
| 6 | regression: **237ns/cert → 438ns/cert**. |
| 7 | |
| 8 | The changes were a single commit containing multiple independent improvements. |
| 9 | This plan applies them one at a time, benchmarking after each, to identify the |
| 10 | culprit and find a way to keep the correctness improvements without the |
| 11 | performance cost. |
| 12 | |
| 13 | ## Baseline |
| 14 | |
| 15 | | Commit | Description | ns/cert | |
| 16 | |--------|-------------|---------| |
| 17 | | `80caac2d1` | safety lints (pre-change baseline) | 239 | |
| 18 | | `19dd2c187` | all changes combined | 438 | |
| 19 | |
| 20 | ## Results |
| 21 | |
| 22 | | Step | Change | ns/cert | Delta | |
| 23 | |------|--------|---------|-------| |
| 24 | | 0 | Baseline | 239 | — | |
| 25 | | 1 | Non-minimal DER length validation | 228 | -11 (noise) | |
| 26 | | 2 | Tag enum + multi-byte tag rejection | 469 | **+241 (2x regression)** | |
| 27 | |
| 28 | **Root cause identified: Step 2.** The `Tag` enum decode is the sole culprit. |
| 29 | Replacing `buffer.decode::<u8>()` with `buffer.decode::<Tag>()` (which does a |
| 30 | multi-byte check + a 10-arm match) on every TLV in the cert doubles parse time. |
| 31 | |
| 32 | Steps 3–5 were not measured because the regression is entirely in Step 2. |
| 33 | |
| 34 | ## Fix Strategy |
| 35 | |
| 36 | Keep the correctness benefits (multi-byte tag rejection) without the `Tag` enum |
| 37 | overhead on the hot path. Options: |
| 38 | |
| 39 | **Option A: Validate in `Tlv::decode`, keep `u8` tag internally.** |
| 40 | Add the multi-byte rejection check (`tag & 0x1F == 0x1F`) directly in |
| 41 | `Tlv::decode` as a single branch on the raw `u8`. Keep `Tlv.tag` as `u8`. |
| 42 | Convert to `Tag` enum only at comparison sites (which are cold relative to |
| 43 | decode). This preserves the type safety at comparison points while keeping the |
| 44 | hot path as a single byte read + one branch. |
| 45 | |
| 46 | **Option B: `#[inline(always)]` on `Tag::decode`.** |
| 47 | The match may not be inlining into `Tlv::decode`. Force it and see if the |
| 48 | compiler optimizes it away for the common case. Quick to test but may not help |
| 49 | if the issue is the match itself rather than call overhead. |
| 50 | |
| 51 | **Option C: Reorder — decode tag as `u8`, validate + convert lazily.** |
| 52 | `Tlv` stores the raw `u8`. Add a `Tlv::tag()` method that returns `Tag` (doing |
| 53 | the match). The typed `der_element!` wrappers call `tag()` once. Untyped |
| 54 | `Tlv` decodes that skip the tag pay no match cost. |