Skip to content

perf: scalar hot-path optimizations in the parser - #616

Open
enomado wants to merge 3 commits into
ron-rs:masterfrom
enomado:perf/scalar-parser-hotpath
Open

enomado wants to merge 3 commits into
ron-rs:masterfrom
enomado:perf/scalar-parser-hotpath

Conversation

@enomado

@enomado enomado commented Jul 16, 2026

Copy link
Copy Markdown
Contributor

Six independent, behavior-preserving micro-optimizations on the deserializer's parser hot path (src/parse.rs). Each is a self-contained change; none alters observed behavior (same values, same error kinds, same error positions).

Changes

  • parse_integer_digits — f: fn(&mut T, u8) -> bool → impl Fn, plus a byte loop with inline hex decode instead of char_indices() + decode_hex(c)?. The fn-item was coerced to a fn pointer, i.e. an indirect call per digit that defeated inlining of checked_add/checked_sub. As a generic it monomorphizes and inlines. The is_int_char pre-scan guarantees every byte is in [0-9a-fA-F_], so the byte path is equivalent to the char path.
  • float() — borrow the digit slice as Cow::Borrowed when it contains no _ separator (the common case) instead of allocating a String per float. Underscores still take the strip-and-validate path.
  • find_double_dot() — a memchr-free two-byte scan replacing str::find("..") at the two float-run sites. For a 2-byte needle str::find spins up StrSearcher + an internal memchr per number, even though a typical float has no "..".
  • next_chars_while_from_len — impl Fn predicate + byte scan instead of str::find(|c| !condition(c)). Non-ASCII bytes still decode one char, so unicode predicates (is_whitespace_char, is_ident_raw_char/XID) are preserved.
  • skip_ws — fast-exit when the next byte is a non-whitespace, non-/, ASCII token (the overwhelmingly common case in compact RON), replicating exactly the single no-op iteration of the slow path (including the prev_cursor update the error-span tests rely on).
  • prev_cursor — store just the byte offset (usize) instead of a full ParserCursor; only the offset is ever read (in span_error).

Verification

  • Full test suite: 456 passed / 0 failed.
  • Grammar-conformance differential (a PEG reference transcribed from docs/grammar.md, diffed against the parser over a 64-input battery): agrees.
  • Fuzzing (cargo fuzz, from_str / raw_value / roundtrip): ~9.6M total iterations, no crashes / panics / leaks.

Measurements

Differential RON-vs-serde_json microbenchmark, taskset-pinned perf stat -e instructions (deterministic), before = this branch's merge base:

workload before after Δ
integers 253.7e9 156.0e9 −38%
floats 434.5e9 257.3e9 −41%
strings 30.5e9 24.2e9 −21%
mixed 280.9e9 180.0e9 −36%

Throughput on the same benchmark (single run): ints 66→131 MB/s, floats 82→133 MB/s, strings 215→314 MB/s.

Follows the same pattern as the recently merged #608 / #610 quadratic-parsing fixes; these are the pure-throughput follow-ups from the same investigation.

enomado and others added 3 commits October 22, 2026 00:15
Six independent, behavior-preserving optimizations on the deserializer's parser
hot path (parse.rs), all validated against the full test suite (456 tests), a
grammar-conformance differential, and ~9.6M fuzz iterations across from_str /
raw_value / roundtrip with no crashes.

- parse_integer_digits: `f: fn(...)` -> `impl Fn`, byte loop + inline hex decode
  instead of `char_indices()` + `decode_hex(c)?`. The fn-item was coerced to a fn
  pointer, an indirect call per digit that defeated inlining of checked_add/sub.
- float(): borrow the digit slice as Cow::Borrowed when it has no `_` separator
  (the common case) instead of allocating a String per float.
- find_double_dot(): a memchr-free two-byte scan replacing `str::find("..")` at
  the two float-run sites; the 2-byte needle otherwise spins up StrSearcher + an
  internal memchr per number.
- next_chars_while_from_len: `impl Fn` predicate + byte scan instead of
  `str::find(|c| !condition(c))`, keeping unicode semantics on non-ASCII bytes.
- skip_ws: fast-exit when the next byte is a non-whitespace ASCII non-comment
  token (the overwhelmingly common case in compact RON).
- prev_cursor: store just the byte offset (`usize`) instead of a full
  `ParserCursor` (only the offset is ever read, in span_error).

Measured with a differential RON-vs-serde_json microbenchmark, taskset-pinned
`perf stat -e instructions` (deterministic):

  intloop    253.7e9 -> 156.0e9 instr  (-38%)
  floatloop  434.5e9 -> 257.3e9 instr  (-41%)
  strloop     30.5e9 ->  24.2e9 instr  (-21%)
  mixed      280.9e9 -> 180.0e9 instr  (-36%)
- next_chars_while_from_len: перенос сигнатуры под rustfmt (>100 cols)
- unwrap() -> expect(): crate денит clippy::unwrap_used в non-test коде
  (i всегда на границе UTF-8 char, chars().next() = Some по инварианту)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
crate денит unwrap/expect/panic/unreachable в non-test коде. Заменить
.expect() на match с graceful break на невозможном None (i всегда на
границе UTF-8 char, chars().next() = Some по инварианту).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
@enomado
enomado force-pushed the perf/scalar-parser-hotpath branch from d817729 to 105b3b2 Compare October 21, 2026 21:28
@JosieGr

JosieGr commented Nov 2, 2026

Copy link
Copy Markdown

We hit this independently in a 2D game engine that stores scenes as RON. With ron 0.12.3, an 8,000-entity scene (1.7 MB) takes ~37 ms to load on one thread, and ~90% of that is the parser itself. As a local experiment I made just the borrow-the-digit-slice change from this PR, plus skipping the inf/NaN checks when a number starts with a digit. Typed f32 throughput went from 55 to 112 MB/s, and our scene load dropped ~14% (named struct fields are our remaining cost, which the skip_ws/next_chars_while changes here should also help). Thanks for the work. We'd be glad to see this reviewed.

@enomado

enomado commented Nov 2, 2026

Copy link
Copy Markdown
Contributor Author

@JosieGr
Nice to hear it. Sorry for offtopic but yep, we decide that this text formats is too niche. For big scenes try some binary stuff like protobuf. We have some research how different stuff like CADs store their scenes you can try and migrate to best.

Comment thread src/parse.rs
pub fn next_chars_while_from_len(
&self,
from: usize,
condition: impl Fn(char) -> bool,

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What is the perf impact of only changing fn to impl Fn, but without changing the body?

Comment thread src/parse.rs
}

let digit = Self::decode_hex(c)?;
// Inline decode_hex: `b` is a guaranteed ASCII hexdigit; the `_` arm is a

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How much does the decode_hex call cost? Perhaps the function could be split into decode_hex and decode_hex_ascii, where the first calls the second after the ascii check, and the second just works on bytes

Comment thread src/parse.rs
None => return Ok(()),
Some(&b)
if b < 0x80
&& !matches!(b, b' ' | b'\t' | b'\n' | b'\r' | 0x0B | 0x0C)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What are the last two escapes?

@JosieGr

JosieGr commented Nov 3, 2026

Copy link
Copy Markdown

Thanks, that's a fair point for very large scenes. We plan to keep RON as the editable source of truth (diffable, hand-fixable) and add a binary copy baked at build time later on, so the parser speed mainly matters for editor loads.

You mentioned some research on how CAD tools store their scenes. Is that written up anywhere public? I'd be keen to read it before designing the binary side.

@enomado

enomado commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor Author

@juntyr sorry, i'm a bit lose courage of this. yes, it is AI slop. but it demonstrates some optimisation opportunities. If you adopt this all honour is yours 🥇 . Do what ever you want. I'm comfortable with my own forks of all rust ecosystem, since being banned in rust repos.

@JosieGr claude can do the best. just mention you want migrations, versions. We checked freecad format mostly. all this staff balance betwenn human readable formats and embeddable binary (lets say you have Vec<(f32,3)> mesh)

This branch has not been deployed

No deployments
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.

3 participants