⚡ Speed up ArrayArbitrary generate hot path#7019
Open
dubzzz wants to merge 2 commits into
Open
Conversation
Optimise the per-call cost of `array(arb).generate(...)`: - Inline `applyBias` into `generate` — the previous helper returned an object literal on every call. The biased branches are restructured as a plain `if/else` ladder so no temporary object is allocated. - Cache `biasedMaxLength(this.minLength, this.maxGeneratedLength)` and `this.minLength === this.maxGeneratedLength` (`isFixedLength`) on the instance — both depend only on constants captured at construction. - Skip the depth-context `try/finally` when `depthImpact === 0`, which is the common case for arrays that do not opt into a depth identifier. - Short-circuit `buildSlicedGenerator` when there are no custom slices (`hasNoCustomSlices`). The inner loop then calls `this.arb.generate` directly instead of going through the generator wrapper. - Pre-size `items`, `vs`, `itemsContexts` to the known length and write by index instead of growing via `safePush`.
|
@fast-check/ava
fast-check
@fast-check/jest
@fast-check/packaged
@fast-check/poisoning
@fast-check/vitest
@fast-check/worker
commit: |
Contributor
⏱️ Benchmark ResultsClick to expand |
dubzzz
added a commit
that referenced
this pull request
May 29, 2026
Cover the arbitraries targeted by the in-flight ⚡ performance PRs with a single key case each, mirroring the existing integer benchmark: - array(integer()) generate (#7019) - tuple(integer(), integer()) generate (#7018) - constantFrom(...) generate (#7020) - string() generate (#7021) - integer().chain(.) generate (#7025) - integer().filter(.) shrink (#7024, shrink-only hot path) https://claude.ai/code/session_01892QKEatye539h87ym1bFp --------- Co-authored-by: Claude <noreply@anthropic.com>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Description
fc.array(...)is one of the most widely-used arbitraries:fc.string,fc.set,fc.uniqueArray,fc.subarray, every typed-array arbitrary,fc.commands,fc.lorem,fc.webUrl, and many user composites all go throughArrayArbitrary.generate. This PR shaves several per-call overheads from that path without changing observable behaviour for a given seed.What changes
applyBias. The helper returned a fresh{ size, biasFactorItems? }object every call. The two pieces are now plain locals ingenerate, and the biased branches are written as a singleif/elseladder so no intermediate object is allocated. (Tucked behind twooxlint-disable-next-line no-dupe-else-ifbecausemrng.nextIntis impure and produces a different value on each roll — the duplicated condition shape is intentional.)biasedMaxLength(minLength, maxGeneratedLength)involvesMath.log+Math.floorand was recomputed on every generate; it is now memoised on the instance ascachedBiasedMaxLength.minLength === maxGeneratedLengthis also stored asisFixedLengthto keep the bias dispatch cheap.try/finallywhendepthImpact === 0. This is the dominant case for arrays not opted into a depth identifier. V8 cannot easily hoist thetryitself; the explicit branch avoids the wrapping.buildSlicedGeneratorwhen no custom slices are configured. A constructor-timehasNoCustomSlicesflag is the common case; the inner loop then callsthis.arb.generate(mrng, biasFactorItems)directly instead of going through a generator wrapper that allocates a closure object per call.items,vs,itemsContextsto the known length and write by index.safePushis replaced by indexed writes (new Array(N)is sealed behindoxlint-disable-next-line unicorn/no-new-arraybecause the array is fully populated by the immediately-following loop).Background reading
try/finallyperturbs V8 optimisation: https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#2-unsupported-syntax.Observable behaviour
No public API change. Same seed → same generated value, same shrink ordering. One agent-tried optimisation (skipping
lengthArb.generateonisFixedLengtharrays) was reverted because it would change the RNG state —uniformInt(rng, N, N)still draws once, and skipping it would diverge seeds.The whole
test/unit/arbitrary/array.spec.ts+_internals/ArrayArbitrary.spec.tssuite (27 tests) passes unchanged; the broadertest/unit/arbitrary/sweep (2085 tests + 1 skipped) also passes.Numbers
Median of 13 runs × 4 s, paired against
main:array<int>defaultarray<int>maxLength: 10array<int>fixed length 50array<bool>defaultarray<int>empty (fixed 0)array<constant>fixed length 100array<int>size: 'small'array<int>size: 'xlarge'array<int>default biasedstringdefault (uses array internally)stringmaxLength: 10integerdefault (control, untouched)The
array<constant>numbers are the largest because they benefit the most from thehasNoCustomSlicesshort-circuit + the absence of any inner-allocation pressure — the per-iteration cost essentially collapses tothis.arb.generate.Re-runnable benchmark:
Why this is patch-level
No API change. No behaviour change for a given seed. The single file touched is
_internals/ArrayArbitrary.ts. No new tests needed: the existing suites pin the contract this PR preserves.Checklist
— Don't delete this checklist and make sure you do the following before opening the PR
pnpm run bumpor by following the instructions from the changeset bot🐛(vitest) Something...) when the change targets a package other thanfast-checkGenerated by Claude Code