Repository navigation
#89: faster class creation, Integer/Range step and first/last, expand_path, pack, reflection paths - #182
Merged
Conversation
…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]>
|
Warning Review limit reachedEnable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
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. View limit details
|
32 of 36 tasks
This was referenced Nov 10, 2026
Merged
Merged
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.
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 withtaskset, 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
Struct.newand class creation (Blocked by perf: JIT/OSR for case/when and Hash/Array access, rule-free first calls, precompiled startup library #84)Integer#step,Range#step/first/last,Kernel#IntegerFile.expand_pathis ~2.4× CRuby (Blocked by perf: JIT/OSR for case/when and Hash/Array access, rule-free first calls, precompiled startup library #84)instance_variable_get,dup,clone,respond_to?,sendandinspect(Blocked by perf: JIT/OSR for case/when and Hash/Array access, rule-free first calls, precompiled startup library #84)Also ticked on #89, already done on master:
Integer << 2**31raises RangeError (#171).1. Class creation (ce3dd1f)
Three causes:
AddDependentClasswalked the superclass's whole dependent list before adding to it. Object's list holds every live class, so eachClass.newscanned all of them. A class registering from its own constructor cannot be in any list yet, so it now skips the scan.RuleVersionSetstopped 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.Struct.newandData.definecalledklass.__send__andklass.define_singleton_methodon the new class. A new receiver gets a new rule every time. They now useinstance_method(...).bind_call, whose sites always see an UnboundMethod, as the prelude's Errno setup already does.Class.newClass.new { def m = 1 }Class.new { define_method(:x) { 1 } }Class.new { attr_accessor :a }Struct.new(:a, :b)Struct.new(:a, :b, keyword_init: true)Struct.new(:a) { def x = 1 }Data.define(:a, :b)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_methodon it) and the interpreter running the class body.Test:
ModuleClassNew4creates 5000 classes, past the set's limit, then redefines methods on them. It also coversStructandDataat scale.2.
Integer#stepkeywords,Range#step,Range#first/last(n)(b4f44b1)Integer#step(by:, to:)and#step(limit, by:)always went to the prelude'sNumeric#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#stepwas a preludedef 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##stepit overrode, and itsStepStorage, 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#eachnow givesto_a.last(n), as MRI does (rb_method_basic_definition_p). Before, IronRuby counted the run and answered[9, 10].Range_IntegerFastPaths1had asserted the old answer.1.step(by: 3, to: 10) { }1.step(10, by: 3) { }(1..10).step(3) { }(1..10).step { }(1..100).first(3)(1..100).last(3)(..5).last(2)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_a3.4–3.75 µs on both.Test:
Range_IntegerFastPaths2.3.
File.expand_path(3021c39)RubyUtils.ExpandPathalways gotplatform.CurrentDirectory: agetcwd(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 secondgetcwd.A null base now means "the current directory", and it is read only for a relative path.
File.expand_path,File.absolute_path,File.realpathand the loader pass null.File.expand_path("/usr/lib")File.expand_path("~/x")File.expand_path("x", "/base")File.expand_path("/x/../y", "/z")File.expand_path("a/b")File.absolute_path("a")What is left for a relative path is the
getcwditself, which CRuby pays too.Test:
File_ExpandPathLazyCwd1(skipped on Windows, which has drive letters).4. pack/unpack fixed overhead (b06a587)
["x"].pack("Cy")is still a TypeError for"x", andunpack1still stops before a bad directive later in the format.WriteIntegertakes a Fixnum without theto_intsite, and writes a byte-swapped value with oneWriteinstead of oneWriteByteper byte.[1, 2].pack("C*")[1, 2, 3].pack("NnC")[1, 2, 3].pack("s<l>q")"abcd".unpack("N")"abcd".unpack1("N")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##clonenow takes[Keywords]itself, with the same errors, and the prelude wrapper is removed.parametersandaritystill report MRI's ([[:key, :freeze]], -1).o.instance_variable_get(:@a)o.instance_variable_set(:@a, 1)o.instance_variable_defined?(:@a)o.public_send(:bar)o.cloneo.clone(freeze: false)respond_to?,send,dupandinspectwere 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#Integeroverloads (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 forInteger(12), which just returns its argument.Integer(12)Integer(12.5)Integer("123")The same overload for
Float("1.5")gave no gain, because its time goes to parsing, soFloatis 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.
The erroring examples are the same set on master:
#to_str/#to_intconversions returning the wrong type, andObjectSpace.each_object.Differential scripts against CRuby 4.0.9, master and branch:
absolute_path,realpath, encodings andchdir.@,buffer:,offset:.The branch output is identical to master's, except for the
Range#lastfix above.Not done
raise/rescue(~25×) andthrow/catch. These are now one CLR throw each, and a raise through compiled frames is also a single throw (MethodDefinitionno longer catches and rethrows). What remains is .NET 8's native exception dispatch, ~25 µs here: aSystem::Int32.Parse("x")that fails costs the same. TheDOTNET_LegacyExceptionHandling=0switch 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).MakeArray0is also every[]literal, and[] << xgot ~50 ns slower when the first append had to allocate.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 ** -2goes throughrational.rb. A Float step needsruby_float_stepin C#.🤖 Generated with Claude Code