Repository navigation
Conversation
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>
d817729 to
105b3b2
Compare
|
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 |
|
@JosieGr |
| pub fn next_chars_while_from_len( | ||
| &self, | ||
| from: usize, | ||
| condition: impl Fn(char) -> bool, |
There was a problem hiding this comment.
What is the perf impact of only changing fn to impl Fn, but without changing the body?
| } | ||
|
|
||
| let digit = Self::decode_hex(c)?; | ||
| // Inline decode_hex: `b` is a guaranteed ASCII hexdigit; the `_` arm is a |
There was a problem hiding this comment.
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
| None => return Ok(()), | ||
| Some(&b) | ||
| if b < 0x80 | ||
| && !matches!(b, b' ' | b'\t' | b'\n' | b'\r' | 0x0B | 0x0C) |
|
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. |
|
@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) |
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 ofchar_indices()+decode_hex(c)?. The fn-item was coerced to a fn pointer, i.e. an indirect call per digit that defeated inlining ofchecked_add/checked_sub. As a generic it monomorphizes and inlines. Theis_int_charpre-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 asCow::Borrowedwhen it contains no_separator (the common case) instead of allocating aStringper float. Underscores still take the strip-and-validate path.find_double_dot()— amemchr-free two-byte scan replacingstr::find("..")at the two float-run sites. For a 2-byte needlestr::findspins upStrSearcher+ an internalmemchrper number, even though a typical float has no"..".next_chars_while_from_len—impl Fnpredicate + byte scan instead ofstr::find(|c| !condition(c)). Non-ASCII bytes still decode onechar, 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 theprev_cursorupdate the error-span tests rely on).prev_cursor— store just the byte offset (usize) instead of a fullParserCursor; only the offset is ever read (inspan_error).Verification
docs/grammar.md, diffed against the parser over a 64-input battery): agrees.cargo fuzz,from_str/raw_value/roundtrip): ~9.6M total iterations, no crashes / panics / leaks.Measurements
Differential RON-vs-
serde_jsonmicrobenchmark,taskset-pinnedperf stat -e instructions(deterministic), before = this branch's merge base: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.