Skip to content

Fewer allocations in hot library paths: int yield cache, C# Comparable#clamp, allocation-free [a, b].min/max, block-filled Array#fill - #94

Merged
Largo merged 5 commits into
masterfrom
claude/tender-pasteur-67de3v
Nov 4, 2026
Merged

Largo merged 5 commits into
masterfrom
claude/tender-pasteur-67de3v

Conversation

@Largo

@Largo Largo commented Nov 4, 2026 •

Copy link
Copy Markdown
Owner

Profiling khasinski/doom's bench/benchmark.rb with dotnet-trace showed the renderer allocating ~11 MB per frame. In this environment that allocation costs far more than the dispatch around it. These commits cut the allocation, and the per-element work, in the generic (non-JIT) runtime paths:

  • BlockParam.Yield(int …) overloads. times, upto, step, Range#each over Fixnums, each_index and each_with_index boxed their counter on every iteration. The new overloads take the box from ScriptingRuntimeHelpers.Int32ToObject, the cache for −100..999. Before this, Range#each was 7% of all allocated bytes.
  • Comparable#clamp in C#. It was Ruby in ruby4.rb, so each x.clamp(lo, hi) paid for a method scope, a splat array and a case. The new version follows MRI's cmp_clamp: the same errors, the Range and duck-typed range forms, arity −1, and <=> through a dynamic site.
  • [a, b].min / [a, b].max without the array, as MRI's opt_newarray_send does. ArrayExtremeSite answers from the two elements with the same <=> calls as IListOps.GetExtreme, as long as Array#min (#max) is still the library's own public method and no refinement is active. A redefinition, alias, visibility change or refinement falls back to the call as written. The check is re-done whenever RubyModule.GlobalMethodVersion changes.
  • Array#fill and Array.new(n, value) use a block fill. Fill went through IList's indexer one element at a time, and AddMultiple stored one element at a time. Both now go through RubyArray.Fill and Utils.Fill, which is now Array.Fill (the old loop had a TODO saying "can be optimized for big repeatCount"). Filling a 64,000-element array went from 440 to 235 µs.

Measurements (Release, net8.0, 4-core Linux VM, alternating runs against master 44891067)

master this branch
bench/benchmark.rb, median frame time 28.9–30.6 ms 24.3–26.2 ms
400-frame driver, average frame time 22.3–27.9 ms 19.1–20.4 ms
bytes allocated (driver run) 5.38 GB 3.57 GB

The framebuffer checksum is identical in every run.

Tried and not kept

  • A shortcut for Array#dup that skips the initialize_dup / initialize_copy dispatch. It made no measurable difference: the time is in allocating the copy.
  • GC settings (GCgen0size, server GC, non-concurrent GC, libclrgc). Pauses got shorter, but frame times did not improve.

Testing

  • ruby/spec at the CI pin: spec/language plus spec/core/{array,comparable,integer,range,enumerable,float,kernel,string}. The failure list is identical to master's: Array#fill/Array.new with too-large sizes, two String#byteslice/#[] cases, and the existing Integer bignum-boundary cases.
  • clamp and fill: matrices of argument forms, errors, arity and identity. The output is identical to CRuby's.
  • [a, b].min/max: a matrix of types, errors, evaluation order, a block, a count, a custom <=>, redefinition, alias and refinement. The output is identical to master's.
  • Initializers.Generated.cs was regenerated with regen-initializers.sh. I added the two ReflectionCache.Generated.cs entries by hand, in alphabetical order.

🤖 Generated with Claude Code

https://claude.ai/code/session_01KPwZf6zTBynkVVtAVjXKpW

Integer#times, #upto, #step, Range#each over Fixnums, each_index and each_with_index
yield a C# int counter, which boxed afresh on every iteration. BlockParam.Yield gets
int overloads that take the box from ScriptingRuntimeHelpers.Int32ToObject, so a
counter in -100..999 allocates nothing.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01KPwZf6zTBynkVVtAVjXKpW
It was Ruby in ruby4.rb, so every x.clamp(lo, hi) paid for a method scope, a splat
array and a case on its size. The C# version follows MRI's cmp_clamp: the same
errors, the Range and duck-typed range forms, arity -1, and <=> called through a
dynamic site so a redefined <=> is still honoured.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01KPwZf6zTBynkVVtAVjXKpW
The commonest way Ruby spells the smaller or larger of two values allocated an
object[4] and a RubyArray per evaluation. As long as Array#min (#max) is still the
library's own public method and no refinement is about, the answer is now worked out
from the two elements with the same <=> calls in the same order (MRI's
opt_newarray_send does the same). A redefinition, alias, visibility change or
refinement sends it back to the call as written; the binding is re-checked against
RubyModule.GlobalMethodVersion.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01KPwZf6zTBynkVVtAVjXKpW
@coderabbitai

coderabbitai Bot commented Nov 4, 2026 •

Copy link
Copy Markdown

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

This PR implements Comparable#clamp in C# and adds a specialized runtime path for eligible two-element array literal min and max calls. It also adds integer argument overloads to BlockParam.Yield.

Changes: Comparable clamp

Layer / File(s) Summary
Clamp implementation and Ruby replacement
Src/Libraries/Builtins/Comparable.cs, Src/StdLib/ironruby/ruby4.rb
C# overloads handle bounds, Range values, and range-like objects. They validate arguments, compare bounds, and return the receiver or an applicable bound. The Ruby implementation is removed.

Array literal min and max

Layer / File(s) Summary
Array literal extreme dispatch
Src/Ruby/Compiler/Ast/Expressions/MethodCall.cs, Src/Ruby/Runtime/RubyOps.cs, Src/Ruby/Runtime/Calls/ArrayExtremeSite.cs, Src/Ruby/Runtime/BlockParam.cs
The compiler recognizes eligible two-element array literal calls and sends them to runtime helpers. ArrayExtremeSite checks refinements and method bindings before comparing the elements; it signals when ordinary dispatch should handle the call. BlockParam adds integer argument yield overloads.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Change: Refactor

Sequence Diagram(s)

sequenceDiagram
  participant MethodCall
  participant RubyOps
  participant ArrayExtremeSite
  participant Protocols
  MethodCall->>RubyOps: Pass two literal items and min/max flag
  RubyOps->>ArrayExtremeSite: Invoke with current Ruby scope and items
  ArrayExtremeSite->>ArrayExtremeSite: Check refinements and method binding
  ArrayExtremeSite->>Protocols: Compare items when the library method applies
  ArrayExtremeSite-->>RubyOps: Return selected item or NotHandled
  RubyOps-->>MethodCall: Return result
  MethodCall->>MethodCall: Use ordinary call path when result is NotHandled
Loading

Possibly related issues

  • Largo/ironruby#89 — The issue identifies Array#min and Array#max performance gaps, and this PR changes the path for two-element array literal calls.

Possibly related PRs

  • Largo/ironruby#50 — Changes refinement activation behavior used by the array extreme path’s refinement check.
  • Largo/ironruby#77 — Addresses integer clamp behavior and the dynamic comparison contract used by this PR’s Comparable#clamp.
  • Largo/ironruby#22 — Changes BlockParam yield handling, which this PR also extends with integer argument overloads.

Suggested reviewers: claude

Merge Risk: Minimal · up to 14b6f

This change reduces allocations in the Doom renderer by caching boxed integers, moving Comparable#clamp to C#, and fast-pathing two-element array-literal min and max. No actionable merge-blocking issue was found, and the reported spec and behavior matrices show no regressions.

Pre-merge checks: Passed 4 · Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 25.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documenta… Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed Passed checks: 4 passed
Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Title check Passed The title clearly identifies the main allocation-reduction changes, including integer yield caching, C# Comparable#clamp, and optimized array-literal min/max. It also mentions Array#fill, which is not…
Full details: Title check

Explanation

The title clearly identifies the main allocation-reduction changes, including integer yield caching, C# Comparable#clamp, and optimized array-literal min/max. It also mentions Array#fill, which is not described in the provided changes.

Full details: Docstring Coverage

Explanation

Docstring coverage is 25.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documentation-only edits and deletions within surviving functions are included; unchanged diff context and fully deleted functions are excluded. Analyzed 8 functions across 6 files.

Resolution

Write docstrings for the functions missing them to satisfy the coverage threshold.

Finishing Touches
Generate docstrings
  • Commit to this branch
  • Create a new PR
Generate unit tests (beta)
  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share
Recent review info
Run configuration
  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: e1328f54-06df-45fb-82b7-ea3ea5a74a1c
Commits

Reviewing files that changed from the base of the PR and between 4489106 and 14b6f27.

Files ignored due to path filters: 2
  • Src/Libraries/Initializers.Generated.cs is excluded by !**/*.generated.*
  • Src/Ruby/Compiler/ReflectionCache.Generated.cs is excluded by !**/*.generated.*
Files selected for processing: 6
  • Src/Libraries/Builtins/Comparable.cs
  • Src/Ruby/Compiler/Ast/Expressions/MethodCall.cs
  • Src/Ruby/Runtime/BlockParam.cs
  • Src/Ruby/Runtime/Calls/ArrayExtremeSite.cs
  • Src/Ruby/Runtime/RubyOps.cs
  • Src/StdLib/ironruby/ruby4.rb

Included review availability: This review used your included allowance. Your plan provides up to 1 included review per hour; 0 remain after this review.

Fill went through IList's indexer one element at a time: an interface call, a
frozen check and a bounds check per element. A RubyArray now fills its backing
store with RubyArray.Fill, and Utils.Fill (whose TODO said "can be optimized for
big repeatCount") is Array.Fill. Filling a 64,000-element array went from 440 to
235 microseconds.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01KPwZf6zTBynkVVtAVjXKpW
AddMultiple stored the value one element at a time; it now uses the same block
fill as Array#fill.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01KPwZf6zTBynkVVtAVjXKpW
@Largo Largo changed the title Doom renderer: fewer allocations in the generic call path (~20% faster) Fewer allocations in hot library paths: int yield cache, C# Comparable#clamp, allocation-free [a, b].min/max, block-filled Array#fill Nov 4, 2026
@Largo
Largo merged commit 9cbeb64 into master Nov 4, 2026
8 checks passed
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.

2 participants