Skip to content

bug: dstr: safe formatting is 6.6–58.2× slower than C #1296

Closed

Description

@zackees

Part of #1295.

Context and reproduction

Class: performance regression / release-gate investigation.

The safe formatter calls self.replace(placeholder, val) for each non-null replacement. replace checks a slice at every byte and builds a new output Vec, including the no-match scan. The C implementation uses strstr to locate matches. Reached by the C ABI dstr_safe_printf with $1: $2 and a 128/4096-byte first value.

Benchmark Rust ns C ns Rust/C Paired run ratio range
dstr/safe_printf/128 1424.165 215.802 6.599× 5.926–9.126×
dstr/safe_printf/4096 26033.556 447.311 58.200× 58.135–70.310×

Location

Profiling evidence

A 10 s cycles:u profile of dstr/safe_printf/4096/rust collected 1,966 samples, no lost samples: 67.88% self cycles in __memcmp_avx2_movbe, with inline stack through Dstr::replace → safe_printf → dstr_safe_printf; 19.70% in Dstr::replace. This supports optimizing the search loop. Profiles include fixture setup; the paired timings exclude setup.

Proposed fix and failing-test sketch

Replace byte-at-a-time match checking with an efficient substring search and avoid unnecessary no-match output construction. Preserve sequential placeholder replacement, byte strings, embedded-NUL behavior, aliases, and existing capacity semantics.

Acceptance criteria

  • Establish RED evidence before coding: reproduce the affected benchmark cases with five paired release passes, median and range; isolate a stable regression from measurement noise. Keep the baseline/command/CPU/source identity.
  • Implement only demonstrated causes, then show GREEN: affected hot-path median Rust/C ratios at or below 1.10 on the same release target, or an explicit separate acceptance of the remaining measured user impact under docs/rust-port/release-criteria.md. For unstable candidates, a reproducible negative result with evidence can close the investigation without a code change.
  • Preserve the public C ABI and allocation contracts. Run affected Rust unit/layout/differential tests and unchanged C tests against both libobs variants for any implementation change; document any inapplicable tier. Keep malformed-input/fuzz and floating-point parity coverage where relevant. Do not edit public headers or existing C tests to make a change pass.
  • Recheck related cases to show the optimization does not transfer cost elsewhere; record absolute times as well as ratios. Functional correctness alone does not close a performance issue.

Decisions

P1: largest stable measured regression; investigate before the Rust default flip. Benchmark input sizes stay together because they exercise the same implementation path. No claim is made that a synthetic ratio equals user-visible frame-time impact.

Measurement context

Measured on 2026-10-17, AMD Ryzen 7 3700X, Linux x86_64, CPU affinity 7, Rust 1.98.1, GCC 15.2.0. Five complete passes of all 70 paired Criterion comparisons; 30 samples/case/pass, 0.1 s warmup, 0.4 s measurement, 10,000 resamples. Values below are medians of the five pass medians. The ratio range contains the five paired Rust/C ratios; the reported median ratio divides the two backend medians.

CARGO_PROFILE_BENCH_DEBUG=1 RUSTFLAGS='-C force-frame-pointers=yes' \
  uv run rust/tools/benchmarks/record.py --cpu 7 --repeats 5 --output baseline.json

The optimized profiling build completed in 40.99 s. Recorded end-of-run HEAD: b56092cc66a979b2f543da20846b965c3517ac36. The checkout was shared and HEAD moved during work; the recorder's source fingerprint stayed unchanged across all five timing passes: 5eea3716b30cf03831eacbc1f06711c2c622f915ebd8945a6940e6fab9d0d422. Source links use fetched master; the fingerprint identifies the measured benchmark/implementation input set. Baseline JSON SHA-256: 9517eb96c66a484cf305a13758a856d893f4608ee454c1a6ea16f693f62c4f26.

This was a shared host. The application build ran on CPUs 0–3 during part of the CPU-7 benchmark run, and other workloads were present. Wide ranges and nanosecond-scale differences require confirmation on quiet release hardware. A descriptive threshold crossing is not proof of statistical significance. The C oracle uses Cargo's optimized C build, rather than full OBS C IPO; profiling frame pointers also affect tiny call costs. No cross-platform or whole-application speedup/slowdown is inferred from shim benchmarks. dstr/printf_control remains C in both configurations and is excluded from Rust regression decisions.

Local evidence: /home/niteris/dev/obs-rust/reports/obs-profile-20261017/ contains baseline.json (per-run medians/confidence intervals), build logs, perf data/reports, assembly, runtime logs/maps/results, and the profiling harness. Raw Criterion samples are in target/criterion, baselines ports-20261017T172745Z-1 through ports-20261017T172745Z-5. Key evidence is reproduced here so triage does not depend on local file access.

Activity

  1. zackees commented on Oct 18, 2026

    @zackees
    MemberAuthor

    Claiming. Plan: Dstr::replace searches with a real substring finder (memchr::memmem if it's already in the workspace, else windows() on the first byte then a slice compare), returns early without allocating when nothing matches, and builds the output in one pass. Parity with C is kept (Tier 3 oracle). RED is the existing Rust/C performance bound for dstr/safe_printf from the #668 benchmarks, plus the parity tests staying green.

  2. added
    claimed
    on Oct 18, 2026
  3. removed
    claimed
    on Oct 20, 2026
  4. MCPVOT commented on Oct 20, 2026

    @MCPVOT
    Contributor

    Claiming: #1296.

    Read of the code: dstr_safe_printf walks its replacement list and calls self.replace(placeholder, val) once per non-null value. Each replace rescans the whole buffer from byte 0 (a slice compare at every position) and allocates a fresh Vec for the result, even when the placeholder is absent. With $1: $2 and a 4096-byte first value the output is rebuilt twice and the first value is rescanned twice, which is where the 58x comes from; the C side does one strstr walk and copies.

    Plan (one PR):

    1. RED: record the existing dstr/safe_printf/{128,4096} numbers from the crate bench on current master (the issue already documents them; I will re-measure locally so the before numbers are on this commit, and say plainly that a perf change has no failing unit test).
    2. GREEN: replace the repeated replace calls with one pass - find the earliest placeholder with memchr(b'$') + a match check, copy the untouched prefix once, append the value, continue from after it. No per-call full-buffer copy, no no-match scan of the whole buffer per placeholder. Keep the exact output bytes and the existing $1-to-$3 semantics.
    3. Correctness gate: the existing dstr tests and the C-vs-Rust parity tests for dstr_safe_printf must stay green (output text unchanged), then re-run the bench alternating Rust/C so the ratio, not the raw number, is the claim.

    If the ratio does not drop materially I will say so in the PR instead of shipping it.

  5. added
    claimed
    on Oct 20, 2026
  6. MCPVOT commented on Oct 20, 2026

    @MCPVOT
    Contributor

    Releasing this: it looks already resolved on current master, so I am not going to ship a change for it.

    Measured with the issue's own benchmark (cargo bench -p obs-c-oracle --bench port_comparison -- safe_printf, $1: $2 with the obs ... seed), current master dd39d8aed, three runs, criteria intervals:

    case this issue reports measured now (rust / c) ratio
    dstr/safe_printf/128 6.599x 292.9 / 253.0 ns, 341.8 / 329.4 ns, 413.9 / 303.3 ns 1.04-1.36x
    dstr/safe_printf/4096 58.200x 789.2 / 920.2 ns, 923.3 / 1030.1 ns, 975.4 / 1001.3 ns 0.86-0.97x (rust faster)

    The 58x case is gone, and at 4096 bytes the Rust path is now the faster one. What the issue describes as the cause is also no longer the code:

    • find_from is memchr-accelerated (first byte) and then compares the tail, i.e. the strstr behaviour it asks for.
    • replace_plan returns ReplacePlan::None without copying or allocating when the placeholder is absent, so the no-match full-buffer scan is already skipped.

    Both landed with #1297's dstr work, which is why this one went stale.

    The only thing left above the project's 10% bound is the 128-byte case at ~1.1-1.4x, on a ~300 ns microbenchmark where the intervals are wide; that is not the 6.6x the issue describes and probably not worth a PR on its own. If you want it tightened anyway, the remaining cost is the copy(format) plus one grow-rebuild per placeholder, and a single-pass formatter that only falls back to the sequential dstr_replace chain when a value itself contains $ would remove it without changing output.

    Happy to take it if you would rather see that than close this.

  7. removed
    claimed
    on Oct 20, 2026
  8. zackees commented on Oct 20, 2026

    @zackees
    MemberAuthor

    yes please take it

  9. MCPVOT commented on Oct 21, 2026

    @MCPVOT
    Contributor

    Opened #1619 for this: the format is now walked once and the result written once, with the four-pass chain kept for the case where a value itself contains a $ (and for arguments that point into the destination's buffer).

    dstr/safe_printf/128 goes from 1.042 to 0.763 of the C time, 4096 from 0.837 to 0.794 (3 alternating runs per side, C as in-run control).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions