Skip to content

#89: faster class creation, Integer/Range step and first/last, expand_path, pack, reflection paths - #182

Merged
Largo merged 6 commits into
masterfrom
claude/issue-89-round3
Nov 9, 2026
Merged

Largo merged 6 commits into
masterfrom
claude/issue-89-round3

Conversation

@Largo

@Largo Largo commented Nov 9, 2026

Copy link
Copy Markdown
Owner

Part of #89. Six of its unticked items, one commit each. Behaviour is unchanged except where noted, and the expected outputs of the new tests are CRuby 4.0.9's.

All numbers: Release net8.0 builds of fork/master (91fa636) and of this branch, main-thread CPU (/proc/thread-self/stat), pinned with taskset, interleaved master / branch / branch / master. Every case runs a warm-up pass first; each figure is the best of 5 rounds of at least 200 ms. CRuby is 4.0.9 on the same core.

#89 items this addresses

Also ticked on #89, already done on master: Integer << 2**31 raises RangeError (#171).

1. Class creation (ce3dd1f)

Three causes:

  • A duplicate scan per new class. AddDependentClass walked the superclass's whole dependent list before adding to it. Object's list holds every live class, so each Class.new scanned all of them. A class registering from its own constructor cannot be in any list yet, so it now skips the scan.
  • A cliff at 4096 classes. A shared call-site rule's RuleVersionSet stopped growing at 4096 versions. After that, every new class got a rule of its own, built and compiled for one class: about 0.3 ms per call on a new class. A program that made more than ~3500 classes stayed on that slow path. A full set now starts over. A dropped version that is still live is added again on its next miss.
  • Calls on the class just made. Struct.new and Data.define called klass.__send__ and klass.define_singleton_method on the new class. A new receiver gets a new rule every time. They now use instance_method(...).bind_call, whose sites always see an UnboundMethod, as the prelude's Errno setup already does.
master branch CRuby
Class.new 120–150 µs 2.3 µs 0.55 µs
Class.new { def m = 1 } 125–138 µs 6.0–6.5 µs 1.4 µs
Class.new { define_method(:x) { 1 } } 145–290 µs 29 µs 2.2 µs
Class.new { attr_accessor :a } 88–180 µs 25–26 µs 3.0 µs
Struct.new(:a, :b) 863–888 µs 34–36 µs 6.0 µs
Struct.new(:a, :b, keyword_init: true) 813–963 µs 35–40 µs 6.5 µs
Struct.new(:a) { def x = 1 } 700–850 µs 21–29 µs 6.0 µs
Data.define(:a, :b) 425–450 µs 91–94 µs 4.8 µs

The harness makes thousands of classes per case, so master is past the cliff here. A fresh process sees master at about 50–60 µs for Class.new { define_method ... }.

What is left is mostly binding call sites for each new class's singleton (define_method, undef_method on it) and the interpreter running the class body.

Test: ModuleClassNew4 creates 5000 classes, past the set's limit, then redefines methods on them. It also covers Struct and Data at scale.

2. Integer#step keywords, Range#step, Range#first/last(n) (b4f44b1)

  • Integer#step(by:, to:) and #step(limit, by:) always went to the prelude's Numeric#step(*args, **kw). With Fixnums, a limit and a non-zero step, they now run the C# loop the positional form already uses. Everything else still goes to the prelude.
  • Range#step was a prelude def step(*args, &block). It is C# again: a Fixnum range with a positive Fixnum step loops in C#. Every other call goes to the same prelude code, now __ir_range_step__(args). The old C# #step it overrode, and its StepStorage, are removed.
  • Range#first(n) and #last(n) build the run in C# for a plain Fixnum range.

Fix: #last(n) on a Range subclass with its own #each now gives to_a.last(n), as MRI does (rb_method_basic_definition_p). Before, IronRuby counted the run and answered [9, 10]. Range_IntegerFastPaths1 had asserted the old answer.

master branch CRuby
1.step(by: 3, to: 10) { } 3.0–4.5 µs 0.28 µs 0.70 µs
1.step(10, by: 3) { } 2.8–4.0 µs 0.28 µs 0.45 µs
(1..10).step(3) { } 1.1–1.25 µs 0.16–0.19 µs 0.35 µs
(1..10).step { } 1.5–1.6 µs 0.28 µs 0.55 µs
(1..100).first(3) 1.0–1.5 µs 0.10 µs 0.45 µs
(1..100).last(3) 0.9–1.2 µs 0.10 µs 0.19 µs
(..5).last(2) 0.8–1.2 µs 0.11 µs 0.16 µs

The slow paths measure the same as before: a Float range is 3.1–3.3 µs on both, and (1..10).step(3).to_a 3.4–3.75 µs on both.

Test: Range_IntegerFastPaths2.

3. File.expand_path (3021c39)

RubyUtils.ExpandPath always got platform.CurrentDirectory: a getcwd(2) and a string on every call. That happened even for an absolute path or one with a base directory. A relative path paid twice, because the base (the current directory itself) was expanded again against a second getcwd.

A null base now means "the current directory", and it is read only for a relative path. File.expand_path, File.absolute_path, File.realpath and the loader pass null.

master branch CRuby
File.expand_path("/usr/lib") 2.0–2.25 µs 0.44–0.50 µs 0.48 µs
File.expand_path("~/x") 2.4–2.5 µs 0.80–0.88 µs 0.40 µs
File.expand_path("x", "/base") 2.4–2.75 µs 0.88–0.94 µs 0.68 µs
File.expand_path("/x/../y", "/z") 0.75–1.6 µs 0.63–0.65 µs 0.55 µs
File.expand_path("a/b") 5.3–7.8 µs 3.0–3.1 µs 2.75 µs
File.absolute_path("a") 4.25–5.25 µs 3.0–3.1 µs 2.6 µs

What is left for a relative path is the getcwd itself, which CRuby pays too.

Test: File_ExpandPathLazyCwd1 (skipped on Windows, which has drive letters).

4. pack/unpack fixed overhead (b06a587)

  • Formats are parsed once. The directives of the last 256 formats (up to 128 characters each, per direction) are cached. Before, every call parsed the format again through an iterator.
  • Errors still come at the same point. For a format with an error, the directives before the error are cached, and the error is raised afresh after they have run. So ["x"].pack("Cy") is still a TypeError for "x", and unpack1 still stops before a bad directive later in the format.
  • Integers are written in one go. WriteInteger takes a Fixnum without the to_int site, and writes a byte-swapped value with one Write instead of one WriteByte per byte.
master branch CRuby
[1, 2].pack("C*") 313–344 ns 250–300 ns 219 ns
[1, 2, 3].pack("NnC") 375–500 ns 300–350 ns 275–313 ns
[1, 2, 3].pack("s<l>q") 375–500 ns 300–350 ns 263 ns
"abcd".unpack("N") 200–275 ns 175–250 ns 194–206 ns
"abcd".unpack1("N") 200–250 ns 175–225 ns 144 ns

Test: Pack_CachedFormats1.

5. instance_variable_get/set, public_send, clone (71b7d9c)

  • instance_variable_get/set/defined? take a Symbol or String name directly instead of going through the to-symbol conversion site. They do what the site's rule does for those two types; any other name still goes to the site.
  • public_send(:name) has an overload with no argument list, so there is no array and no splatted site. Its site keeps public visibility (no implicit self, IsInteropCall), so private and protected methods stay unreachable.
  • Kernel#clone(freeze: nil) was a prelude method with a keyword parameter in front of the C# #clone. The C# #clone now takes [Keywords] itself, with the same errors, and the prelude wrapper is removed. parameters and arity still report MRI's ([[:key, :freeze]], -1).
master branch CRuby
o.instance_variable_get(:@a) 100 ns 63–69 ns 45 ns
o.instance_variable_set(:@a, 1) 100–238 ns 81–88 ns 50 ns
o.instance_variable_defined?(:@a) 88–94 ns 60–75 ns 41 ns
o.public_send(:bar) 175–188 ns 50–55 ns 105 ns
o.clone 406–438 ns 250 ns 206 ns
o.clone(freeze: false) 600–650 ns 375 ns 363 ns

respond_to?, send, dup and inspect were already at or below CRuby: 40–50 ns, 45 ns, 188–225 ns and 750 ns, against CRuby's 48–55, 75, 175 and 1300 ns.

Test: Kernel_ReflectionFastPaths1.

6. Kernel#Integer overloads (92bf25e)

Integer(x) with no base and no keywords now has overloads for a String, a Fixnum and a Float. The general overload takes four conversion storages, an optional base and a [Keywords] parameter. Dispatching to it cost more than the conversion: about 100 ns for Integer(12), which just returns its argument.

master branch CRuby
Integer(12) 105 ns 40–43 ns 29–31 ns
Integer(12.5) 131 ns 40–48 ns 31 ns
Integer("123") 150–163 ns 75–88 ns 53 ns

The same overload for Float("1.5") gave no gain, because its time goes to parsing, so Float is unchanged.

Test: Kernel_IntegerOverloads1.

Verification

  • IronRuby.Tests, Debug net8.0, full run: 0 failures, including the 7 new tests (PASSED, exit 0). Both TFMs build. The seven new or changed tests also pass on net10.0.

  • ruby/spec at CI's SPEC_REF (dda28d04) / MSPEC_REF (b79c65ed), Release net8.0, master against this branch: the same results on both.

    dir examples failures errors
    core/class 54 0 0
    core/struct 170 0 1
    core/data 89 0 2
    core/module 1050 0 4
    core/range 606 0 0
    core/integer 598 0 2
    core/numeric 326 0 0
    core/kernel 2230 0 4
    core/basicobject 172 0 3
    core/objectspace 107 0 20
    core/array/pack 1675 0 0
    core/string/unpack + unpack1_spec 1510 0 0
    core/file expand_path, absolute_path, realpath, realdirpath 68 0 0
    library/delegate 74 0 0

    The erroring examples are the same set on master: #to_str/#to_int conversions returning the wrong type, and ObjectSpace.each_object.

  • Differential scripts against CRuby 4.0.9, master and branch:

    • class creation: 5000 classes, Struct, Data.
    • step / first / last: about 100 cases.
    • expand_path: 16 paths × 9 bases, plus absolute_path, realpath, encodings and chdir.
    • pack/unpack: 25 directives × 16 values, error ordering, @, buffer:, offset:.
    • reflection: about 40 cases.
    • Integer()/Float(): 36 arguments × 6 forms.

    The branch output is identical to master's, except for the Range#last fix above.

Not done

  • raise/rescue (~25×) and throw/catch. These are now one CLR throw each, and a raise through compiled frames is also a single throw (MethodDefinition no longer catches and rethrows). What remains is .NET 8's native exception dispatch, ~25 µs here: a System::Int32.Parse("x") that fails costs the same. The DOTNET_LegacyExceptionHandling=0 switch of .NET 9+ has no effect on 8.
  • RubyOps.MakeArray0. An empty rest array is not measurably cheaper without the 4-slot buffer (rest() stays at 162 ns). MakeArray0 is also every [] literal, and [] << x got ~50 ns slower when the first append had to allocate.
  • Copy-on-write strings and the DLR's MathUtils.ToString. These need a design change, as the issue says.
  • Float("1.5"), Integer(s, exception: false), 3 ** -2, Float #step. The first two are parsing and keyword cost. 3 ** -2 goes through rational.rb. A Float step needs ruby_float_step in C#.

🤖 Generated with Claude Code

Largo and others added 6 commits November 9, 2026 21:05
…89)

Three costs made Class.new, Struct.new and Data.define 50-200x CRuby:

- A new class registered with its superclass and modules through
  AddDependentClass, which first walked the whole dependent list for a
  duplicate. Object's list holds every live class, so each Class.new
  scanned all of them. A class registering from its own constructor
  cannot be in any list yet; it now skips the scan.
- A shared call-site rule's RuleVersionSet stopped growing at 4096
  versions, after which every new class got a rule of its own, built
  and compiled for one class (~0.3 ms a call). A program that makes
  more than ~3500 classes fell off that cliff for good. A full set now
  starts over; a dropped version that is still live is added again on
  its next miss.
- Struct.new and Data.define called klass.__send__ and
  klass.define_singleton_method on the class they had just made: a new
  receiver, so a new rule every time. They now go through
  instance_method(...).bind_call, whose sites always see an
  UnboundMethod, as the prelude's Errno setup already does.

Release net8.0, main-thread CPU, interleaved master/branch (harness
makes thousands of classes per case):

  Class.new                    120-135 us -> 2.3 us   (CRuby 0.55 us)
  Class.new { def m = 1 }      100-119 us -> 6.6 us   (CRuby 1.7 us)
  Class.new { define_method }  238-295 us -> 43 us    (CRuby 2.8 us)
  Struct.new(:a, :b)           463-500 us -> 40 us    (CRuby 7.8 us)
  Struct.new(..., kw_init)     825-1075 us -> 44-48 us (CRuby 8 us)
  Data.define(:a, :b)          488-600 us -> 138-144 us (CRuby 6.5 us)

Test: ModuleClassNew4 (5000 classes past the set's limit, then
redefinitions; Struct/Data at scale), output checked against CRuby 4.0.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The prelude methods the issue lists for Integer and Range, where the
common Fixnum case paid for a Ruby entry point:

- Integer#step(by:, to:) and #step(limit, by:) went to the prelude's
  Numeric#step (*args, **kw) every time. With Fixnum values, a limit
  and a non-zero step they now run the loop Integer#step already has
  for its positional form; every other combination (another keyword,
  the limit given twice, no limit, step 0, Floats) goes on to the
  prelude as before.
- Range#step was a prelude `def step(*args, &block)`. It is C# again
  (RangeOps.Step): a Fixnum range with a positive Fixnum step loops
  there, and everything else is the prelude's code, renamed
  __ir_range_step__ and handed the arguments as an Array. The old C#
  #step it overrode (and its StepStorage) is gone.
- Range#first(n) and #last(n) of a plain Fixnum range build the run
  in C# instead of calling __first_n__/__last_n__.

#last(n) now follows MRI for a Range subclass with an #each of its
own: to_a.last(n) (MRI checks rb_method_basic_definition_p), where
IronRuby counted the run and answered [9, 10] instead of what #each
yields. Range_IntegerFastPaths1 asserted the old answer.

Release net8.0, main-thread CPU, interleaved master/branch:

  1.step(by: 3, to: 10) { }   3.3-5.5 us  -> 0.6-0.75 us (CRuby 0.43 us)
  1.step(10, by: 3) { }       2.6-6.0 us  -> 0.25-0.63 us (CRuby 0.43 us)
  (1..10).step(3) { }         1.25-1.75 us -> 0.23-0.38 us (CRuby 0.29 us)
  (1..10).step { }            1.6-2.5 us  -> 0.36-0.63 us (CRuby 0.53 us)
  (1..100).first(3)           1.1 us      -> 0.11-0.19 us (CRuby 0.30 us)
  (1..100).last(3)            0.93-0.95 us -> 0.12-0.21 us (CRuby 0.13 us)
  (..5).last(2)               0.88-0.91 us -> 0.13-0.18 us (CRuby 0.09 us)

The slow paths (a Float range, no block) measure the same as before.

Test: Range_IntegerFastPaths2 (Fixnum boundaries, keyword errors,
subclasses), expected output from CRuby 4.0.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
RubyUtils.ExpandPath was always handed platform.CurrentDirectory, a
getcwd(2) and a string per call, even for an absolute path or one with
a base directory. A relative path paid twice: the base path, itself
the current directory, was expanded again against a second getcwd.

ExpandPath now takes a null base for "the current directory" and only
reads it for a relative path; a given base is expanded against it only
when the base itself is relative. File.expand_path, File.absolute_path,
File.realpath and the loader's path expansion pass null.

Release net8.0, main-thread CPU, interleaved master/branch:

  File.expand_path("/usr/lib")        1.9-2.5 us -> 0.35-0.43 us (CRuby 0.48 us)
  File.expand_path("~/x")             2.4-3.5 us -> 0.68-1.5 us  (CRuby 0.38 us)
  File.expand_path("x", "/base")      2.4-2.5 us -> 0.72 us      (CRuby 0.63 us)
  File.expand_path("a/b")             6.6 us     -> 3.5-3.6 us   (CRuby 2.6 us)
  File.absolute_path("a")             4.8-5.0 us -> 2.6 us       (CRuby 2.6 us)

What is left of "a/b" is the getcwd itself, which CRuby pays too.
A differential script (16 paths x 9 bases, expand_path and
absolute_path, realpath, encodings, after chdir) gives CRuby 4.0's
output on master and on this branch alike.

Test: File_ExpandPathLazyCwd1.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Part of the fixed cost of Array#pack and String#unpack was reading the
format again on every call, through an iterator. The directives of the
last 256 formats (up to 128 characters, per direction) are now kept.
A format with an error in it keeps the directives before the error, and
the error is raised afresh, by reading the format again, once those have
run - where reading as the work went along raised it - so
["x"].pack("Cy") is still the TypeError for "x" and unpack1 still stops
before a bad directive further on.

WriteInteger converts a Fixnum without the to_int conversion site and
writes each value with one Write instead of one WriteByte per byte when
the byte order is swapped ('n', 'N', 's>' ...).

Release net8.0, main-thread CPU after a warm-up pass, interleaved
master/branch, two runs:

  [1, 2].pack("C*")        313-344 ns -> 250-300 ns (CRuby 219 ns)
  [1, 2, 3].pack("NnC")    375-500 ns -> 300-350 ns (CRuby 275-313 ns)
  [1, 2, 3].pack("s<l>q")  375-500 ns -> 300-350 ns (CRuby 263 ns)
  "abcd".unpack("N")       200-275 ns -> 175-250 ns (CRuby 194-206 ns)
  "abcd".unpack1("N")      200-250 ns -> 175-225 ns (CRuby 144 ns)

A differential script (25 integer directives x 16 values, error
ordering, '@', comments, buffer:, offset:, 400 distinct formats) gives
CRuby 4.0's output on master and on this branch alike.

Test: Pack_CachedFormats1.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
- instance_variable_get/set/defined? converted a Symbol or String name
  through the to-symbol conversion site; they now take those two
  directly, as the site's rule does (ConvertToSymbolAction.
  TryConvertStringOrSymbol), and leave everything else to it.
- public_send(:name) went through the params overload: an argument
  Array, then a splatted call site. A no-argument overload calls a
  site of its own with the same visibility (no implicit self,
  IsInteropCall), so private and protected methods stay unreachable.
- Kernel#clone(freeze: nil) was a prelude method with a keyword
  parameter in front of the C# #clone, so every #clone paid a Ruby
  keyword entry. The C# #clone now takes [Keywords] itself and reports
  the same errors (unknown keyword(s), unexpected value for freeze,
  wrong number of arguments); the prelude wrapper is gone. Its
  parameters/arity are still MRI's ([[:key, :freeze]], -1, from
  InternalMethods.Signatures).

Release net8.0, main-thread CPU after a warm-up pass, interleaved
master/branch:

  o.instance_variable_get(:@A)        100 ns     -> 63-69 ns   (CRuby 45 ns)
  o.instance_variable_set(:@A, 1)     100-238 ns -> 81-88 ns   (CRuby 50 ns)
  o.instance_variable_defined?(:@A)   88-94 ns   -> 60-75 ns   (CRuby 41 ns)
  o.public_send(:bar)                 175-188 ns -> 50-55 ns   (CRuby 105 ns)
  o.clone                             406-438 ns -> 250 ns     (CRuby 206 ns)
  o.clone(freeze: false)              600-650 ns -> 375 ns     (CRuby 363 ns)

respond_to?, send, dup and inspect, which the issue also lists,
measure at or below CRuby already (40-50, 45, 188-225 and 750 ns).

A differential script (names as Symbol/String/subclass/to_str/bad,
visibility, method_missing, keywords and blocks through public_send,
clone's freeze:, singleton and initialize_clone hooks, delegate.rb)
gives the same output on master and on this branch; it differs from
CRuby 4.0 only in the wording of public_send's NoMethodError for
private/protected methods, as on master.

Test: Kernel_ReflectionFastPaths1.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
#89 lists Kernel#Integer among the core methods with a large ratio,
"where the keyword-argument wrapper call is most of the cost". The
wrapper is C# now, but its one overload takes four conversion
storages, an optional base and a [Keywords] parameter, and the
binder's dispatch to it cost more than the conversion itself: ~100 ns
for Integer(12), which only answers its argument.

Integer(string), Integer(fixnum) and Integer(float) - no base, no
keywords - now have overloads of their own that do what the general
one does for them (ParseInteger, the value, ClrFloat.ToInt). Every
other call, and Kernel.Integer, goes to the general one as before.

Release net8.0, main-thread CPU after a warm-up pass, interleaved
master/branch:

  Integer(12)      105 ns     -> 40-43 ns (CRuby 29-31 ns)
  Integer(12.5)    131 ns     -> 40-48 ns (CRuby 31 ns)
  Integer("123")   150-163 ns -> 75-88 ns (CRuby 53 ns)

The same for Float("1.5") measured no gain - its time goes to parsing -
so Float is unchanged.

A differential script (36 arguments: strings with prefixes, spaces,
underscores, NUL, non-ASCII digits, a String subclass, Fixnums,
Bignums, Floats with NaN/Infinity, nil, true, #to_int, #to_f, ...;
each through Integer(), Integer(x, exception: false), Integer(x, 8),
Float() and Kernel.Integer) gives the same output on master and on this
branch, and CRuby 4.0's except for one pre-existing difference in how
Float("12")'s error message shows the string.

Test: Kernel_IntegerOverloads1.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@coderabbitai

coderabbitai Bot commented Nov 9, 2026

Copy link
Copy Markdown

Warning

Review limit reached

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

  • Ask an admin to enable usage-based reviews

Open in CodeRabbit

Reviews can continue after your included limit without a manual trigger. An admin must approve usage-based billing.

Next included review available in 33 minutes.

Check out review usage here.

View limit details

Limit details: You’ve used the included review currently available. Your 66 included PR review attempts over the past 7 days set your current allowance at 1 review per hour.

Learn how review limits work.

Review configuration:

Run configuration

Commits

Reviewing files that changed from the base of the PR and between 7c3648f and 92bf25e.

Files ignored due to path filters: 1

  • Src/Libraries/Initializers.Generated.cs is excluded by !**/*.generated.*
Files selected for processing: 16

  • Src/IronRuby.Tests/RubyTests.cs
  • Src/IronRuby.Tests/Runtime/EvalTests.cs
  • Src/IronRuby.Tests/Runtime/IntegerTests.cs
  • Src/IronRuby.Tests/Runtime/IoTests.cs
  • Src/IronRuby.Tests/Runtime/MethodTests.cs
  • Src/IronRuby.Tests/Runtime/MiscTests.cs
  • Src/Libraries/Builtins/FileOps.cs
  • Src/Libraries/Builtins/Integer.cs
  • Src/Libraries/Builtins/KernelOps.cs
  • Src/Libraries/Builtins/RangeOps.cs
  • Src/Libraries/Builtins/RubyEncoder.cs
  • Src/Ruby/Builtins/RubyClass.cs
  • Src/Ruby/Builtins/RubyModule.cs
  • Src/Ruby/Runtime/Calls/RuleVersionSet.cs
  • Src/Ruby/Runtime/RubyUtils.cs
  • Src/StdLib/ironruby/ruby4.rb
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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.

1 participant