Skip to content

perf(booking): SmallVec for BookingResult::matched and Inventory::positions #1069

Closed

Description

@robcohen

Problem

Two booking-hot Vec fields where the typical case is 0-1 elements:

```rust
// crates/rustledger-core/src/inventory/mod.rs:97
pub struct BookingResult {
pub matched: Vec,
// ...
}

// crates/rustledger-core/src/inventory/mod.rs:277
pub struct Inventory {
positions: Vec,
simple_index: FxHashMap<InternedStr, usize>, // O(1) for no-cost positions
// ...
}
```

BookingResult::matched

For STRICT booking (the default), exactly one lot is matched per posting. Every booking call allocates a Vec to hold a single Position (or zero, for augmenting postings).

```rust
// crates/rustledger-core/src/inventory/booking.rs:338, 774
let matched: Vec = matching.into_iter().cloned().collect();
```

SmallVec<[Position; 1]> would keep the common case on the stack, eliminating the per-booking heap allocation.

Inventory::positions

For most accounts the inventory holds a handful of positions (often just 1-3 lots over an account's lifetime). The flat Vec<Position> already gets O(1) currency lookup via simple_index, so the iteration cost isn't the issue — it's the heap allocation cost when constructing/cloning inventories.

SmallVec<[Position; 4]> would handle the common case inline. Accounts with hundreds of lots (long-held stock positions) still spill to the heap — same behavior as today.

Proposed approach

  1. Add smallvec = "1" to workspace Cargo.toml (not currently a dep — grep -l smallvec Cargo.toml crates/*/Cargo.toml returns nothing).
  2. Change BookingResult::matched: Vec<Position> → SmallVec<[Position; 1]>.
  3. Change Inventory::positions: Vec<Position> → SmallVec<[Position; 4]>.
  4. Update all .collect::<Vec<_>>() call sites in crates/rustledger-core/src/inventory/booking.rs (lines 338, 774, and others).
  5. Verify rkyv serialization compatibility — SmallVec has an rkyv feature flag.

Expected impact

  • STRICT booking (most common): one fewer heap allocation per posting. For a 100k-transaction load with ~3 postings each, that's ~300k allocations saved.
  • Inventory clones: many code paths clone inventories for snapshots (BQL, validation, plugin pipelines). Inline storage reduces clone cost when positions fit.
  • Cache locality: inventories with few positions become cache-friendlier.

Audit context

Items 3a + 3b from the recent perf audit.

Activity

  1. added
    performance
    on May 11, 2026
  2. robcohen commented on May 11, 2026

    @robcohen
    MemberAuthor

    Closing — the meaningful half of this issue shipped in #1077.

    What landed

    BookingResult::matched: Vec<Position> → SmallVec<[Position; 1]> (PR #1077, merged in bad3311c)

    STRICT booking always produces exactly one matched lot per reducing posting; FIFO / LIFO frequently match a single lot too. The SmallVec switch eliminates the per-booking heap allocation in the common case. Public API kept stable via pub(crate) on the MatchedLots type alias.

    What was deferred (and won't be re-attempted as proposed)

    Inventory::positions: Vec<Position> → SmallVec<[Position; N]> — measured as a regression, reverted.

    Added small-N benches (inventory_add/0..3, new inventory_clone/0..10) and ran a before/after comparison with SmallVec<[Position; 1]>:

    Bench Vec baseline SmallVec[1] Δ
    inventory_add/0 9.8 ns 16.9 ns +74%
    inventory_add/1 97 ns 98 ns ~0%
    inventory_add/3 235 ns 303 ns +26%
    inventory_clone/0 13.6 ns 23.4 ns +72%
    inventory_clone/1 51.6 ns 68.6 ns +32%
    inventory_clone/10 295 ns 412 ns +38%

    Root cause: Inventory also carries two FxHashMap fields (simple_index, units_cache) that dominate the clone cost. The ~50 ns alloc I expected to save on the single-position case got eclipsed by the ~100 ns spent cloning the hashmaps, and the larger struct hurts cache locality across all clone sizes. SmallVec's union representation also doesn't vectorize as cleanly as Vec's memcpy.

    The benches stayed in crates/rustledger-core/benches/inventory_bench.rs so any future attempt has the baseline to measure against.

    Re-open criteria

    This experiment becomes worth retrying if either:

    1. The FxHashMap fields on Inventory become lazy-allocated (Option<Box<FxHashMap<…>>> or similar) — that would change the clone-cost math and the inline-Position-savings might dominate again.
    2. Position's layout shrinks meaningfully (current ~104 B) — smaller inline storage cost makes SmallVec<[Position; N]> more attractive.

    Until then, Vec<Position> stays.

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

    performance

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions