Repository navigation
Description
These came up while profiling and benchmarking 2016-era code against CRuby 3.3 for #78, #79, #81, #83, #85–#88 and #90–#92. They were left alone on purpose: most are in 2026 code (largely the Ruby prelude, Src/StdLib/ironruby/ruby4.rb), in the DLR or in the .NET runtime, so they were out of scope for those PRs. Items under "Blocked by #84" are in files the open PR #84 changes, so they were left until it lands.
All numbers come from Linux, net8.0, Release builds. They are rough micro-benchmark figures, measured while other builds were running.
Strings and regexps
-
String#end_with?on a long binary string is extremely slow. Addressed by Fix the cheap performance gaps from #89 (Hash, Array, Enumerable, String, Range, Encoding, Marshal, Digest, Integer) #95: ~4.7 ms → ~0.4 µs per call on a 100 KB string. The UTF-8 boundary tests now also match CRuby's for invalid bytes.- 500k calls on a 100 KB string did not finish in a benchmark.
- The cause is
MutableStringOps.EndsOnCharacterBoundary(2026), which walks every character and allocates for each one. - For single-byte encodings the answer is always true, so a fast path is likely a one-line fix.
-
MatchData.Createcloned the whole input string on every=~(~74 µs on a 24 KB string, against ~0.4 µs in CRuby). This is addressed by MatchData shares the subject's immutable string; fnmatch patterns translated once #90. -
String#dup,+,stripandhashon ~100 KB strings are 10× or more slower than CRuby.- Most of the cost is .NET large-object-heap copies; CRuby shares the buffer on copy.
- Copy-on-write or a shared-buffer scheme would fix it, but that is a larger design change.
StringIO#readof the whole buffer has the same cause: it copies, where CRuby shares (~240 µs against ~0.3 µs on 650 KB).- Partly fixed by #89: copy-on-write strings (dup/clone/String.new/StringIO#read), hash without copying, faster ASCII literals #186 (copy-on-write). Measured 2026-11-10 on master 9673b97 (Release; net8.0 / net10.0 / CRuby 4.0.9, main-thread CPU,
tasksetto one core, warm-up, best of 5, two interleaved runs):s.dup0.26 / 0.19 µs (CRuby 0.06),String.new(s)0.10 / 0.09 µs (CRuby 0.15), whole-bufferStringIO#readof 650 KB 0.11 / 0.09 µs (CRuby 0.12),s.dup << "x"62 / 47 µs (CRuby 9–67, depending on its heap). - Still open:
s + "x"56 / 46 µs (CRuby 7.9, ~6–7×: one large-object-heap copy of the UTF-16 array plus the gen-2 GCs it triggers, see #89: copy-on-write strings (dup/clone/String.new/StringIO#read), hash without copying, faster ASCII literals #186),stripwith a leading blank 58 / 50 µs (CRuby 0.1: it shares the tail, IronRuby's content has no offset),rstrip0.38 / 0.34 µs (CRuby 0.07),hash76 / 77 µs (CRuby 23, ~3.3×: Marvin over 2 bytes per character). - Addressed by #89: share suffix and middle slices of long strings; hash long ASCII strings as bytes #195 (merged):
- Contents get a start offset, so a long slice from anywhere shares the array:
strip,lstrip,s[n..],byteslice,slice!'s result and split fields. The rule is the same as for prefixes: at least 256 items and at least half the array. An offset slice is never written in place; the string swaps in a copy before its first write. - Long (128+) ASCII strings hash their characters as bytes, Marvin per process seeded. Short strings keep
String.GetHashCode. - net8.0 / net10.0 / CRuby 4.0.9, measured as above:
stripwith a leading blank: 59–60 / 54–55 → 0.4–0.9 / 0.65–0.9 µs (CRuby 0.14)lstrip: ~70 / 62 → ~0.5 / 0.5 µss[1..]: 58 / 54 → 0.2–0.4 / 0.2–0.3 µs (CRuby 0.15)byteslice(1..)of a byte string: ~70 / 50–61 → 0.2–0.3 µshashof 100 KB: 75–85 / 75–92 → 40–45 / 41–45 µs (CRuby 24)strip.hash: 115 → 45 µsstrip =~ /y/: 122–150 / 95–117 → 61–64 / 54–60 µs
- Small strings and Hash lookups with short keys are unchanged.
- Still open:
s + "x"(unchanged at ~56–75 µs, CRuby 8.75). The cost is the large-object-heap allocation and the gen-2 GCs it triggers: withDOTNET_GCLOHThreshold=0x200000it is ~10 µs, but that is a process-wide GC policy decision. Building a long ASCII sum as bytes halved its cost but made a following regexp ~30 % slower (the result has to switch back to characters), so it was dropped.hash~1.8× CRuby (Marvin vs SipHash speed).- Addressed by Integer.sqrt: Karatsuba square root; String#hash: SipHash-1-3 for long ASCII strings #202 (open): long ASCII strings hash with SipHash-1-3 under a random per-process key (CRuby's hash; ~1.5× Marvin's speed per byte). Short strings and non-ASCII characters keep Marvin, so short keys are unchanged. A non-ASCII UTF-8 string held as bytes now decodes once for its hash instead of validating three times. Measured 2026-11-11 (Release, thread CPU, one core, ≥0.6 s warm-up, best of 5, three interleaved rounds, box heavily loaded so ranges are wide; net10.0 / net11.0): 100 KB 48–52 / 44–46 → 30–37 / 31–39 µs (CRuby 25–41), 1 MB 531–689 / 488–508 → 354–434 / 323–404 µs (CRuby 294–389), 1 KB 699–798 / 1020–1104 → 444–608 / 411–721 ns (CRuby 299–455),
("é" * 500).hash2.3–3.0 / 1.9–2.3 → 1.1–1.6 / 1.0–1.5 µs (CRuby 0.34–0.43). 2.44Meql?pairs across representations, encodings, offsets and CLR strings: 0 hash mismatches. - Left: non-ASCII strings held as bytes are still ~3× CRuby: .NET validates/decodes non-ASCII UTF-8 at ~0.6 ns/byte, and hashing the UTF-8 bytes directly would make strings held as characters pay a transcode instead.
XxHash3was not taken (a NuGet dependency, and no claim to resist flooding).
- Addressed by Integer.sqrt: Karatsuba square root; String#hash: SipHash-1-3 for long ASCII strings #202 (open): long ASCII strings hash with SipHash-1-3 under a random per-process key (CRuby's hash; ~1.5× Marvin's speed per byte). Short strings and non-ASCII characters keep Marvin, so short keys are unchanged. A non-ASCII UTF-8 string held as bytes now decodes once for its hash instead of validating three times. Measured 2026-11-11 (Release, thread CPU, one core, ≥0.6 s warm-up, best of 5, three interleaved rounds, box heavily loaded so ranges are wide; net10.0 / net11.0): 100 KB 48–52 / 44–46 → 30–37 / 31–39 µs (CRuby 25–41), 1 MB 531–689 / 488–508 → 354–434 / 323–404 µs (CRuby 294–389), 1 KB 699–798 / 1020–1104 → 444–608 / 411–721 ns (CRuby 299–455),
- A slice that is then appended to still copies twice, as before.
- Addressed by Strings: long ASCII String#+ held as bytes; a slice that is appended to is copied once #207 (open), measured 2026-11-11 (Release net11.0, thread CPU, one core, warm-up, best of 5, master/branch interleaved; box heavily loaded; CRuby 4.0.9), 100 KB:
s[1..] << "x"153–180 → 54–72 µs (CRuby 10),stripwith a leading blank and then concat 155–191 → 55–58,s.byteslice(1..) << "x"204–236 → 116–129 (CRuby 11). The slice is copied once, with room for the append.s + "x": a long ASCII sum is held as bytes, and a regexp match decodes it once into a CLR string that becomes the content: 63–71 → 43–48 µs (CRuby 9–11);(s + "x").hash107–131 → 68–78 (CRuby 50);bytesize68–79 → 33–42;=~unchanged (117–158 → 139–144, CRuby 67). What is left ofs + "x"is the GC cost: a gen-0 collection costs ~0.85 ms in IronRuby against ~0.09 ms in a bare .NET program (card marking, stack roots, survivors), runtime-wide and not string code. Non-ASCIIhashheld as bytes was looked at and left: SipHash over UTF-16 is not faster than .NET 11's Marvin, a fused decode+hash loop was 1.5–3× slower, and the decode itself (Utf8.ToUtf16, 0.5–1.9 ns/byte) is the cost.
- Addressed by Strings: long ASCII String#+ held as bytes; a slice that is appended to is copied once #207 (open), measured 2026-11-11 (Release net11.0, thread CPU, one core, warm-up, best of 5, master/branch interleaved; box heavily loaded; CRuby 4.0.9), 100 KB:
- Contents get a start offset, so a long slice from anywhere shares the array:
- Fresh string literals are slow to create and to read as bytes.
- StringIO line readers, fresh-literal bytes, Integer/Float exception: false, Array#inject/minmax, zip with a Range #114: a literal switched to bytes through the escaping encoder the first time anything wanted bytes, even for ASCII text.
"hello world\n".bytesizetook ~420 ns (CRuby ~62); it now takes ~200 ns, because the ASCII check and the conversion use vectorizedSystem.Text.Ascii. - Still open: creating the literal itself takes ~100 ns, against 51 ns in CRuby.
- Fixed by #89: copy-on-write strings (dup/clone/String.new/StringIO#read), hash without copying, faster ASCII literals #186:
v = "hello world\n"72–81 / 55–65 ns against CRuby's 53–85 ns, and"hello world\n".bytesize67 / 72 ns against 63 ns (net8.0 / net10.0, 2026-11-10; both include thewhileloop, ~1 ns in IronRuby and ~14 ns in CRuby).
- StringIO line readers, fresh-literal bytes, Integer/Float exception: false, Array#inject/minmax, zip with a Range #114: a literal switched to bytes through the escaping encoder the first time anything wanted bytes, even for ASCII text.
-
String#sum(MutableStringOps.GetChecksum) catchesOverflowExceptionon its normal path. Addressed by Fix the cheap performance gaps from #89 (Hash, Array, Enumerable, String, Range, Encoding, Marshal, Digest, Integer) #95. -
String#count,#deleteand#squeezeare 30–145× slower than CRuby in a survey benchmark, andString#ljust/centerwith long results is still ~4×.- Fix the cheap performance gaps from #89 (Hash, Array, Enumerable, String, Range, Encoding, Marshal, Digest, Integer) #95 checks ASCII characters against a bitmask and reads the characters once. On 1140 characters,
count("lo")went from ~15.8 to ~6.5 µs (CRuby ~1.1) anddelete("l")from ~13 to ~8.4 µs (CRuby ~1.4). - What is left is mostly per-character overhead in
MutableStringand building the result. - #89: faster Dir.glob, shared Regexp translations, tighter count/delete/squeeze loops #175: the loops are no longer inlined into large methods (the index was spilled). On 1140 characters,
count/deletenow match CRuby;squeezeis ~1.8× andsqueeze(set)~2.8×.ljust/centermeasure the same as CRuby.
- Fix the cheap performance gaps from #89 (Hash, Array, Enumerable, String, Range, Encoding, Marshal, Digest, Integer) #95 checks ASCII characters against a bitmask and reads the characters once. On 1140 characters,
-
StringContent.ContainsInvalidCharactersallocates a char array per call. It is not hot. Addressed by Fix the cheap performance gaps from #89 (Hash, Array, Enumerable, String, Range, Encoding, Marshal, Digest, Integer) #95. -
Regexp.newand interpolated regex literals are ~4× and ~1.8× slower than CRuby.- The time goes to .NET's regex parser and to
RegexpTransformer.SharedState(2026). - A global
Regexcache keyed on (source, options) would help, but it interacts with the per-instance tier-up counting. - Addressed by #89: faster Dir.glob, shared Regexp translations, tighter count/delete/squeeze loops #175: a shared cache, with tier-up still per instance.
Regexp.newwent from ~6.5 µs to 0.33 µs (CRuby 4.1), and an interpolated literal from ~3 µs to 0.48 µs.
- The time goes to .NET's regex parser and to
-
$~.string.classfor a String subclass isString; CRuby gives the subclass. Also, a frozen source is copied rather than returned as itself. Both were already the case before MatchData shares the subject's immutable string; fnmatch patterns translated once #90. Addressed by #89: $~.string after sub, huge shift widths, faster Enumerable#zip and String#count/delete/squeeze #171. -
Dir.globis still ~5–8× slower than CRuby after MatchData shares the subject's immutable string; fnmatch patterns translated once #90. Part of the cost is aFileExists/DirectoryExistscheck per matched entry. Skipping that check would change how broken symlinks are handled.- Addressed by #89: faster Dir.glob, shared Regexp translations, tighter count/delete/squeeze loops #175: entry types come from the listing, and broken symlinks behave as before.
**/*went from ~23 ms to 1.65 ms (CRuby 0.9 ms), so it is now ~1.3–1.8× CRuby.
- Addressed by #89: faster Dir.glob, shared Regexp translations, tighter count/delete/squeeze loops #175: entry types come from the listing, and broken symlinks behave as before.
IO
-
Thin Ruby wrappers in the prelude dominate several IO costs. The C# layer underneath already makes few system calls (checked with strace). Addressed by IO: built-in line/character/write paths, and the line-reader bugs behind them #111:
readlines/each_line/foreachchomp and transcode in C#;getc,readchar,getbyte,readbyte,each_char,ungetcandwriteare built-ins. Everything measured is now about 0.5–1.6× CRuby.readlines(chomp:)was ~36× CRuby; it is ~1.5× now (53 → 3.3 ms on 20k lines).IO#getc,readcharandgetbytewere 13–40×, andungetc~27×. Nowgetcis ~1.5× andgetbyte~0.9×. StringIO#getc reads one character in C# (and fixes invalid-byte splitting); cached method arity; one-shot Digest hashing #92 covered StringIO only, not IO.each_linecost ~2.5 µs per line; it now costs ~0.1 µs.writeandputswere ~6×; they are now ~1.2–1.4×, and StringIO line readers, fresh-literal bytes, Integer/Float exception: false, Array#inject/minmax, zip with a Range #114 takesputsto ~0.7× (3386 → 1871 µs for 10k).- IO: built-in line/character/write paths, and the line-reader bugs behind them #111 also fixed bugs that were already in master, matching CRuby 3.3:
getcon invalid UTF-8;gets/readlineargument parsing;linenowith a limit;encoding:andbinmode:inIO.foreach/readlines;"rt"and universal newline reads;crlf/cr/lfnewline options as write-only decorators.
- One difference is still open:
ungetc("\r")on a universal-newline stream.
-
StringIO#getsand#readare ~2× CRuby in long runs. Much of that is general string-allocation cost. StringIO line readers, fresh-literal bytes, Integer/Float exception: false, Array#inject/minmax, zip with a Range #114 addresses this:getswent from 3496 to 1288 µs on 20k lines (CRuby 1646);readlines(chomp: true)went from 8651 to ~2300 µs (CRuby 1274);puts×10k went from 4168 to 2740 µs (CRuby 2858);linenono longer counts thenilat the end.
readof the whole buffer is listed under the copy-on-write item above.
Collections and iteration
-
Hash#sliceis O(n), because the prelude snapshots the whole hash (~138 µs against 0.4 µs). Addressed by Fix the cheap performance gaps from #89 (Hash, Array, Enumerable, String, Range, Encoding, Marshal, Digest, Integer) #95. -
Hash#eachcopies all entries up front, soHash#first(10)is O(n). Addressed by Fix the cheap performance gaps from #89 (Hash, Array, Enumerable, String, Range, Encoding, Marshal, Digest, Integer) #95, which also coverseach_keyandeach_value. - Several prelude methods have large ratios against CRuby:
Hash#except,Hash#key,sum,sort_by,group_by,tallyandArray#min/max(~24×).- Fix the cheap performance gaps from #89 (Hash, Array, Enumerable, String, Range, Encoding, Marshal, Digest, Integer) #95 moved
Hash#except,Hash#key,Array#sum,Array#min/max(for Fixnums), andtally/group_byover Arrays to C#. Array#sort_bynow compares Fixnum keys directly.- What remains is about 1–4× CRuby and is mostly the general cost of block calls; Enumerable#sum over non-Arrays still uses the prelude.
- Fix the cheap performance gaps from #89 (Hash, Array, Enumerable, String, Range, Encoding, Marshal, Digest, Integer) #95 moved
-
Array#shiftis ~4.5× CRuby, becauseruby4.rbwraps it in a Rubyshift(*args). A C#shift(count)overload would remove the wrapper, but it needs an Initializers regen (Initializers.Generated.csis a perf: JIT/OSR for case/when and Hash/Array access, rule-free first calls, precompiled startup library #84 file). Addressed by Fix the cheap performance gaps from #89 (Hash, Array, Enumerable, String, Range, Encoding, Marshal, Digest, Integer) #95. -
Enumerable#zipwith an Enumerable argument goes throughEnumerator#next, which makes it ~22× slower. Addressed by #89: $~.string after sub, huge shift widths, faster Enumerable#zip and String#count/delete/squeeze #171. -
(1..1000).counttakes ~67 µs, against ~43 ns in CRuby. The prelude'sRange#countcallssuper(Enumerable) instead of returning the size for Integer ranges. Addressed by Fix the cheap performance gaps from #89 (Hash, Array, Enumerable, String, Range, Encoding, Marshal, Digest, Integer) #95. -
RubyOps.MakeArray0allocates a 4-slot array for an empty rest array. This is minor.- Measured in #89: faster class creation, Integer/Range step and first/last, expand_path, pack, reflection paths #182 and left alone: without the buffer
def f(*a); fis no faster (162 ns either way), and[] << x, which also goes throughMakeArray0, gets ~50 ns slower. - Won't change, per #89: faster class creation, Integer/Range step and first/last, expand_path, pack, reflection paths #182's numbers above.
- Measured in #89: faster class creation, Integer/Range step and first/last, expand_path, pack, reflection paths #182 and left alone: without the buffer
Numerics
- These prelude methods have large ratios against CRuby:
- #89: faster class creation, Integer/Range step and first/last, expand_path, pack, reflection paths #182:
Integer#step(by:, to:)3–4.5 µs → 0.28 µs (CRuby 0.45–0.7),Range#step1.1–1.6 µs → 0.16–0.28 µs (CRuby 0.35–0.55),Range#first(n)/last(n)~1 µs → 0.1 µs (CRuby 0.16–0.45),Integer(12)105 → 40 ns andInteger("123")150 → 75–88 ns (CRuby 30 / 53).Range#include?,to_candround(-2)now measure 0.8–1.4× CRuby. Still open:Float("1.5")(~2.5×, parsing),Integer(s, exception: false)(~2.2×),3 ** -2(~3×,rational.rb), Float#step(~6×). Integer#[],**,pow(pow(b, m)~16×),Integer.sqrtandInteger#digits(~11×);- Addressed by #89: Integer#[], Integer.sqrt, pow(b, m), Kernel#Integer parsing and tail calls, Data.define #190 (Integer#[] and the rest of the integer items; Float(),
3 ** -2, huge powers and Float#step are #89: Float() parsing, 3 ** -2, huge powers, Float#step, String#to_c, split and $~ #188's):Integer#[]is C# for the common forms,x[3]338-362 → 48-65 ns,x[2, 3]~1.4-1.75 µs → 52-58 ns,x[2..5]1.3 µs → 50-60 ns (CRuby 23 / 41 / 138), and fixes5[32], nil and zero sizes, empty/reversed ranges (14372-case differential now matches CRuby);Integer.sqrt(2**70)1.2-1.4 µs → 650-675 ns (CRuby 288);12345.pow(5, 1000)162-206 → 95 ns (CRuby 100), and0.pow(x, 0)is 0 as in MRI;Integer("123")110-162 → 62-72 ns,Integer("123", exception: false)300-375 → 212-250 ns (CRuby 119),Integer("123", 10)219-300 → 150-212 ns, a 30-digit string ~3 µs → 0.39 µs (digits in a long; no slowtail.call into library methods of more than six parameters).digitsalready ~1.2× CRuby (312 vs 250 ns). Kernel#Float/IntegerandInteger#step;Range#size,step,first,lastandinclude?;fdiv,to_c, andInteger#roundwith a negative digit count.- Fix the cheap performance gaps from #89 (Hash, Array, Enumerable, String, Range, Encoding, Marshal, Digest, Integer) #95 status:
- Moved to C#:
Integer.sqrt(770 → 88 ns),pow(b, m)(1234 → 174 ns, now with MRI's checks),pow(b)(413 → 32 ns) anddigits(953 → 354 ns). fdiv: has Fixnum overloads (403 → 35 ns).- Fixnum
**: computes in along. - Prelude fast paths:
Integer#[](357 → 211 ns),Float()(~1000 → ~400 ns) andRange#size(593 → 303 ns). - Still open:
Kernel#Integer/#Float, where the keyword-argument Ruby wrapper call is most of the cost;Integer#**behindrational.rb's wrapper;Integer#step;Range#step/first/last/include?;to_c; androundwith a negative digit count.
- Moved to C#:
- Status after #89: Float() parsing, 3 ** -2, huge powers, Float#step, String#to_c, split and $~ #188 and #89: Integer#[], Integer.sqrt, pow(b, m), Kernel#Integer parsing and tail calls, Data.define #190. Measured 2026-11-10 on master 9673b97 (net8.0 / net10.0 / CRuby 4.0.9, set-up as in the Strings item); CRuby's figures include ~14 ns of
whileloop, IronRuby's ~1 ns:- At or below CRuby:
Float("1.5")121 / 111 ns (99),Float("1_000.5")139 / 118 (137), Float#stepandRange#stepover Floats 0.5–0.6×,Integer#step(by:, to:)andRange#step0.5–0.7×,Range#first(3)/last(3)/include?0.2–0.7×,fdiv,round(-2),x[2, 3],x[2..5],pow(b, m),digits(273 / 225 vs 233),Integer("123"),Integer("123", 10)and a 30-digitInteger()(0.8–1.0×). - Within ~2×:
x[3]37 / 38 ns (26),Integer(12)43 / 40 (31),3 ** 562 / 53 (36),3.to_c106 / 78 (58),3 ** -2128 / 112 (69),Integer("123", exception: false)229 / 167 (142),Float("1.5", exception: false)253 / 224 (138),(2**70 + 12345)[2, 3]170 / 290 (116),"1+2i".to_c373 / 334 (173). - Still open:
Range#size350 / 271 ns against 47 (~6–7×; the prelude method makes ~8 dynamic calls, andis_a?/===alone cost ~140–170 ns here against ~45–60 in CRuby),Integer.sqrt(2**70)650 / 450 ns against 247 (1.8–2.6×) andInteger.sqrt(2**2000 + 1)17.6 / 12.0 µs against 5.5 (BigInteger Newton iteration, slow division on net8.0). Integer.sqrtis addressed by Integer.sqrt: Karatsuba square root; String#hash: SipHash-1-3 for long ASCII strings #202 (open): exactUInt128arithmetic from the double's root for 262..2106, Zimmermann's Karatsuba square root (MCA algorithm 1.12, GMP'smpz_sqrtrem) above, so a call costs about one division of half the size instead of several full-width Newton steps. Measured as the String#hash item above (net10.0 / net11.0):Integer.sqrt(2**70)702–1380 / 1268–1368 → 201–270 / 178–268 ns (CRuby 263–526 on that loaded box, 247–268 quiet),Integer.sqrt(2**2000 + 1)15–16 / 9.6–15 → 7.2–8.4 / 4.6–9.1 µs (CRuby 5.1–8.7; steady state on a quieter run 4.1 / 4.2 µs against 6.5), 20k bits 1.3–1.45 / 0.52–0.56 → 0.15–0.19 / 0.34–0.41 ms (CRuby 0.06–0.09), 100k bits 14–17.6 / 8.5–9.9 → 1.3–4.2 / 3.1–5.3 ms (CRuby 0.43–0.6). Exact against CRuby on 1,738 values up to 100k bits (and 26k more in review). What is left above ~10k bits is BigInteger against GMP, with net11.0's slower division.Range#sizeis addressed by #89: subquadratic Integer#to_s, Range#size in C#, per-thread CPU clock #191 (merged): C# for Integer..Integer, Integer...Integer, endless and nil/Float beginnings (CRuby 4.0 errors kept), prelude__size__for the rest. Measured 2026-11-10 (Release, main-thread CPU, one core, warm-up, best of 5, interleaved):(1..10).size330-360 / 300 → 70-77 / 63-70 ns,(1...10).size343-393 / 297-310 → 70-73 / 67-73,(1..).size333-340 / 240-270 → 70-73 / 63-70 (CRuby 47 / 47 / 80, loop included). What is left is the call itself ((1..10).begin~43 ns against ~27).- The "Within ~2×" list is addressed by Numerics (#89): Integer()/Float() keyword fast path, Bignum bit slices, String#to_c scanner #206 (open), measured 2026-11-11 on master 31dc7e6 (Release, one core, net10.0 / net11.0; the box was loaded, so main-thread user instructions per call, loop included, are the measure, CRuby 4.0.9 in brackets):
Integer("123", exception: false)1400–1460 / 1390 → 630–820 / 820 (1500) andFloat("1.5", exception: false)1530–1580 / 1500 → 1040–1170 / 920–1020 (1330), as the JIT's keyword call cache now calls a library entry of Kernel#Integer/#Float without the keyword Hash (redefinition, refinements, visibility changes and TracePoint respected);(2**70 + 12345)[2, 3]1500–1660 / 2400 → 590–740 / 735 (1110), bits read from the Bignum's bytes;"1+2i".to_c2310–2470 / 2155 → 2025–2260 / 1923 (1540), scanner without its copies. Also fixed there:Float(x, exception: true)'s warning line (198) andInteger("", 1)(invalid radix). Left:x[3],Integer(12),3 ** 5,3 ** -2,3.to_c,Range#sizeandis_a?/===are already C# with instruction counts near CRuby's (3 ** 5440 vs 412,3 ** -2754 vs 796,3.to_c666 vs 650,(1..10).size437 vs 459); their time gap is the general cost of a dynamic call and an allocation.
- At or below CRuby:
- #89: faster class creation, Integer/Range step and first/last, expand_path, pack, reflection paths #182:
- The DLR's
MathUtils.ToString(BigInteger, radix)is quadratic. Numerics: Float->Integer and unpack('w') without exceptions, fast to_s(radix), Int64 shifts; Integers in the Int64 range as longs #86 stopped IronRuby from calling it, but other callers in the DLR still pay for it.- Fixed by DLR patch 0106: MathUtils.ToString(BigInteger, radix) in subquadratic time #187 (DLR patch 0106): called through CLR interop on master (2026-11-10), a ~1M-bit value takes 630 / 242 ms in radix 10 (net8.0 / net10.0; ~106 s before), 430 / 265 ms in radix 7 and under 1 ms in radix 16; 100k bits 20 / 8 ms. Every result equals
Integer#to_s.
- Fixed by DLR patch 0106: MathUtils.ToString(BigInteger, radix) in subquadratic time #187 (DLR patch 0106): called through CLR interop on master (2026-11-10), a ~1M-bit value takes 630 / 242 ms in radix 10 (net8.0 / net10.0; ~106 s before), 430 / 265 ms in radix 7 and under 1 ms in radix 16; 100k bits 20 / 8 ms. Every result equals
- IronRuby's own
Integer#to_sis still quadratic for huge Integers. On net10.0 a ~1M-bit Integer takes 5.9 s in radix 10 and 6.9 s in radix 7, and 100k bits 57 / 87 ms; CRuby (GMP) takes 17 / 21 ms and 0.56 / 0.69 ms.ClrBigInteger.ToRadixStringcould hand values above ~1k bits to the patchedMathUtils.ToString(lower-cased), as DLR patch 0106: MathUtils.ToString(BigInteger, radix) in subquadratic time #187 suggests.- Addressed by #89: subquadratic Integer#to_s, Range#size in C#, per-thread CPU clock #191 (merged): a radix that is not a power of two goes to
MathUtils.ToString(lower-cased); radix 10 keepsBigInteger.ToStringbelow 96k bits on .NET 8 and 32k bits on .NET 9+ (measured crossovers). net8.0 / net10.0, same set-up as Range#size: 1M bits radix 10 1370-1540 / 5600-5870 → 640 / 230-240 ms, radix 7 6780-6850 / 6330-6560 → 560-620 / 160-220 ms (CRuby 18 / 20); 100k bits radix 10 14-19 / 12.3 → 12.5-13 / 5.3-7.3 ms, radix 7 69-77 / 67 → 13.5 / 5.6-5.9 ms (CRuby 0.63 / 0.85). Also quadratic and fixed there: format%d %x %o %bof Bignums (once per digit; 100k bits 3.1 s → 23 / 8 ms, CRuby 1.3) andInteger#digits(100k bits 580 → 22 / 7.5 ms, base 1000 195 → 21 / 8.4 ms; CRuby 4.0 / 2.6). Output byte-identical to CRuby for radix 2..36, signs, power-of-radix boundaries and random values up to 100k bits. - Ticked 2026-11-10: no longer quadratic. What is left (~240 ms vs CRuby's 18 ms at 1M bits on net10.0, ~13×) is .NET BigInteger against GMP.
- Addressed by #89: subquadratic Integer#to_s, Range#size in C#, per-thread CPU clock #191 (merged): a radix that is not a power of two goes to
-
Process.clock_gettime(CLOCK_THREAD_CPUTIME_ID)returned process CPU time. Addressed by #89: subquadratic Integer#to_s, Range#size in C#, per-thread CPU clock #191: the calling thread's, viaclock_gettimeon Unix andGetThreadTimeson Windows (a read is also ~1.25 µs instead of ~12 µs on net8.0). Left: CPU spent in a Fiber (worker thread here, the resuming thread in MRI) is not charged to the resuming thread. -
Integer << 2**31raisesRangeError, where CRuby allocates the result. This was already the case before Numerics: Float->Integer and unpack('w') without exceptions, fast to_s(radix), Int64 shifts; Integers in the Int64 range as longs #86. Addressed by #89: $~.string after sub, huge shift widths, faster Enumerable#zip and String#count/delete/squeeze #171: on net8.01 << 2**31builds the 231+1-bit Integer (on net10.0, whose BigInteger is capped near 231 bits, it is NoMemoryError, as MRI raises when the allocation fails). - pack/unpack fixed overhead is ~1.2–2.3× CRuby, spread across directive parsing and the general call path. Addressed by #89: faster class creation, Integer/Range step and first/last, expand_path, pack, reflection paths #182: formats are parsed once (cached), and integers are written without the conversion site and in one write;
[1, 2, 3].pack("NnC")375–500 → 300–350 ns (CRuby 275–313),"abcd".unpack("N")200–275 → 175–250 ns (CRuby ~200). -
Marshal.loadof Floats is ~2.2× CRuby. It uses a Regex per float, in 2026 code. Addressed by Fix the cheap performance gaps from #89 (Hash, Array, Enumerable, String, Range, Encoding, Marshal, Digest, Integer) #95, which replaces the Regex with a byte scan (~1.4× CRuby now). That also fixes leading white space and"1.e5"to matchruby_strtod.
Libraries
- Streaming Digest is quadratic.
Digest#updatekeeps the whole input in memory, anddigestafter each update copies it. Incremental hashing that can be cloned would fix it.- Addressed by Fix the cheap performance gaps from #89 (Hash, Array, Enumerable, String, Range, Encoding, Marshal, Digest, Integer) #95: input past 64 KB streams into an
IncrementalHash, and a no-argumentdigestreads the current hash without copying. - 2000 × 4 KB updates with a
hexdigestafter each went from 14.2 s to 12 ms (CRuby 39 ms). dupusesIncrementalHash.Cloneon net10.0 and replays the streamed chunks on net8.0, which has noClone.- The same PR fixes
update(nil)(now aTypeError) and mixing a UTF-8 chunk with a binary one (it was anEncoding::CompatibilityError).
- Addressed by Fix the cheap performance gaps from #89 (Hash, Array, Enumerable, String, Range, Encoding, Marshal, Digest, Integer) #95: input past 64 KB streams into an
- StringIO
getcon Big5/EUC-KR differs from CRuby where IronRuby'svalid_encoding?disagrees with CRuby's encoding tables. This showed up in 87 of 4,800 random cases.- Addressed by Issue #89 leftovers: EUC-KR table gaps, #92 regression tests, cheaper Thread.new location #184. Big5 and its family already matched CRuby on master (every 1- and 2-byte sequence). EUC-KR did not: .NET's table reads 0xAD-0xAF and 0xFE alone, so
"\xAD\xAD"split into two characters andchars/length/inspectthrew. 16 sequences → 0 differing, and 122 → 0 in 3 × 4,800 random strings. - Left:
scrubof a truncated 3- or 4-byte sequence in EUC-JP, EUC-TW and GB18030 (CRuby replaces it once), and CP51932 accepting 0x80/0xA0/0xFF.- Checked 2026-11-11 for Strings: long ASCII String#+ held as bytes; a slice that is appended to is copied once #207: both already match CRuby on master (fixed by 0eb0fa9); a 118,272-case differential over EUC-JP, EUC-TW, GB18030, CP51932, eucJP-ms and EUC-JIS-2004 finds no
scrub/valid_encoding?difference there. Left: 272 GB18030 cases, four-byte sequences unassigned in .NET's table (~500k codes, more than the private use planes, so no UTF-16 stand-ins), which IronRuby splits and CRuby reads as one character.
- Checked 2026-11-11 for Strings: long ASCII String#+ held as bytes; a slice that is appended to is copied once #207: both already match CRuby on master (fixed by 0eb0fa9); a 118,272-case differential over EUC-JP, EUC-TW, GB18030, CP51932, eucJP-ms and EUC-JIS-2004 finds no
- Addressed by Issue #89 leftovers: EUC-KR table gaps, #92 regression tests, cheaper Thread.new location #184. Big5 and its family already matched CRuby on master (every 1- and 2-byte sequence). EUC-KR did not: .NET's table reads 0xAD-0xAF and 0xFE alone, so
Exceptions and class creation
-
raise/rescueis ~25× CRuby on net8.0 (~16 µs per raise).- Looked at for #89: faster class creation, Integer/Range step and first/last, expand_path, pack, reflection paths #182: a raise/rescue is now a single CLR throw, also through compiled frames, and
throw/catchone or two. What is left (~25 µs here) is .NET 8's native exception dispatch itself: a failingSystem::Int32.Parsecosts the same. - Raising through 20 Ruby frames costs ~606 µs on net8.0, ~159 µs on net10.0 and ~2 µs in CRuby.
- Most of this is the CLR's own exception dispatch through frames that have filters and finally blocks, plus the
StackTracecapture for the backtrace. throw/catchis ~34 µs, against 0.2 µs.- Profiled again in Performance gaps found while optimizing 2016-era code (not yet addressed) #89 (comment), with nothing shipped. A compiled raise through plain frames is one CLR throw, which is the runtime floor. Each frame with an
ensure, or with arescuethat does not match, adds a full catch-and-throw: 22 throws for 20 frames, ~4x the time on net8.0. Each still-interpreted frame adds one too, becauseInterpreter.Runruns finally blocks from a catch. The way out is a real CLR filter plus afinallyforensure-only frames, but that is a DLR, compiler and backtrace change with semantic risk; see the comment. - #89: exceptions through interpreted frames without a rethrow per frame; Thread.new location without a stack walk #189 (DLR patch 0107): an exception now passes an interpreted frame without a catch and rethrow, unless the frame has a handler or a finally with a jump.
- Measured 2026-11-10 on master 9673b97 (net8.0 / net10.0 / CRuby 4.0.9, set-up as in the Strings item), µs per op, compiled (and interpreted with
-X:CompilationThreshold 1000000000): raise through 20 plain frames 131 / 76 (369 / 221), CRuby 2.2; through 20 frames withensure395 / 149 (732 / 354), CRuby 2.8; through 20 frames with a non-matchingrescue400 / 160 (670 / 524), CRuby 4.1; the same pluse.backtrace184 / 114, CRuby 21;throwthrough 20 frames 60 / 23 (147 / 73), CRuby 1.0;catch { throw }22 / 5.4, CRuby 0.2. - Found here: a compiled raise is not at the CLR floor. A raise rescued in its own compiled method costs 70 / 45 µs at stack depth 0, 98 / 73 at depth 50 and 195 / 158 at depth 200 (CRuby ≤ 5), against 24 / 12 µs for a failing
System::Int32.Parse.RubyExceptionData.CaptureTracetakes aSystem.Diagnostics.StackTraceof the whole stack at the catch site on every raise (DebugStackTrace::GetStackFramesInternalis ~40 % of a perf profile); its walk cache only covers interpreted frames, which is why a raise in a loop of a method that is still interpreted measures ~24 / 12 µs. Walking only to the rescuing frame, or deferring the walk until the backtrace is read, would make a raise independent of stack depth. - #89: ensure-only frames without a rethrow; the rescue's stack walk deferred until needed #192 and #89: rescue clauses that cannot match let the exception go through (real first-pass filter) #194 (merged 2026-11-10): ensure-only frames and frames whose rescue clauses cannot match let the exception through with a CLR filter instead of a catch and rethrow, and the catch-site stack walk is deferred until the exception is exposed. net8.0: raise rescued in its own method ~100 → ~25 µs (depth 200: ~325 → ~28 µs), 20 non-matching rescue frames 380–423 → 97–110 µs, throw through 20 ensures ~325 → ~65 µs. Still ~10–25× CRuby; most of what is left is the CLR's own exception dispatch.
- raise: no stack trace until the backtrace is needed, also through ensure (#89) #210 (merged 2026-11-12, after two reviews), measured on net10.0/net11.0. A rescuing compiled frame finds its PrecompiledFrames record by index, so it no longer reads the exception's CLR trace on every raise. A raise through a compiled ensure-only frame is let through before any backtrace is taken; the capture is completed where the exception is caught or exposed. This applies to
raise Klass, msgand toraise "msg", but not to an ensure clause that calls a block, yields, calls super or jumps out, where the DLR rethrows (those still catch, as before). Instructions per op on net11.0: raise rescued in place 58k → 51k (raise "x"54k → 45k); through 1 ensure 359k → 65k (raise "x"380k → 63k); through 20 ensure frames 482k → 292k; inside Mutex#synchronize 141k → 77k. In µs: 12 → 9.3 rescued in place (CRuby 1.1), 80 → 34 through 20 ensures (CRuby 2.8).catch { throw }is unchanged at ~5 µs (CRuby 0.19): ~90% of it is the CLR's own dispatch, and awhenfilter on the catch tag did not measurably help.
- Looked at for #89: faster class creation, Integer/Range step and first/last, expand_path, pack, reflection paths #182: a raise/rescue is now a single CLR throw, also through compiled frames, and
- Class creation is slow: Addressed by #89: faster class creation, Integer/Range step and first/last, expand_path, pack, reflection paths #182: a new class no longer scans its superclass's whole dependent list (every live class, for Object), a shared rule's version set no longer stops growing at 4096 classes (after which every call on a new class built a rule of its own), and Struct.new/Data.define call into the new class through
bind_call.Class.new120–150 µs → 2.3 µs (CRuby 0.55),Struct.new(:a, :b)~870 µs → 35 µs (CRuby 6),Data.define~440 µs → 92 µs (CRuby 4.8). What is left is mostly binding call sites on each new class's singleton. #89: Integer#[], Integer.sqrt, pow(b, m), Kernel#Integer parsing and tail calls, Data.define #190: no attribute reflection in IsBuiltinMethod after each method definition;Data.define(:a, :b)110-120 → 90-100 µs in a fresh process (CRuby ~7); the rest is rule binding and method definition per class.Class.newtakes ~56 µs, against 0.6 µs in CRuby.Struct.newtakes ~160 µs, or ~570 µs withkeyword_init.Data.definetakes ~415 µs.- About two thirds of the time goes to rebinding call sites for the new class (expression-tree building and the light compiler). Call-site binding: read parameter attributes and class getters once per type #88 took ~5 % off; the rest is spread across the DLR.
-
Thread.new.joinis ~1.8–4× CRuby, mostly the cost of creating the operating-system thread.- Issue #89 leftovers: EUC-KR table gaps, #92 regression tests, cheaper Thread.new location #184: most of it was not the OS thread.
Thread.newbuilt the caller's whole backtrace to record itsfile:line; it now stops at one frame, and the per-method attribute reads of every backtrace are cached. Main-thread CPU 350-400 → 275-325 µs (CRuby 37.5 µs, same core, loaded box). Still open: the CLRStackTracecapture itself (about half of what is left) and the OS thread. - #89: exceptions through interpreted frames without a rethrow per frame; Thread.new location without a stack walk #189 removed the CLR stack walk (the caller's location comes from the Ruby frame records). Measured 2026-11-10 on master 9673b97 (net8.0 / net10.0 / CRuby 4.0.9, set-up as in the Strings item):
Thread.new { }.join51 / 54 µs main-thread CPU against CRuby's 23 (~2.3×), and 146 / 147 µs process CPU against 46 (~3.2×). In a perf profile of 100k threads most of the process CPU is on the finalizer thread in the CLR'sThreadStore::RemoveThread(cleaning up dead threads, a walk of the thread list), plusThreadStore::GetThreadListand dependent-handle scanning during GCs on the main thread; IronRuby's own code is ~1 %.- Addressed in part by Thread.new: let finished threads be collected (DLR ThreadLocal, Thread.list registry) #208 (merged): the
RemoveThreadcost came from finished threads that stayed reachable. The DLR'sThreadLocal<InterpretedFrame>held each entry'sThread(new DLR patch 0108 holds a per-thread token instead), andThread.list's registry kept finished threads until its next prune. In a heap dump during the loop, dead threads in the CLR's list dropped from ~4,700 to ~200. 20 joined threads are now collected (0 alive after full GCs, 20 before). Finalizer CPU for 50k threads 0.4–1.2 → 0.14–0.19 s, allocation 6.2–7.7 → 3.1–3.6 KB per thread. Measured 2026-11-11, Release, one core, box at load 13–21; net10.0 / net11.0 / CRuby 4.0.9: main-thread CPU 51–63 / 48–55 → 49–58 / 41–47 µs (CRuby 27–34), process CPU 152–186 / 148–173 → 142–171 / 124–143 µs (CRuby 51–60). What is left is the CLR thread itself: a plain C#new Thread().Start(); Join()loop costs 39–52 / 112–145 µs here. Pooling CLR threads (~8–15 µs per hand-off) was evaluated and not done: a RubyThreadis itsSystem.Threading.Thread, so pooling needs a separate identity object and changes to everyThread.CurrentThreaduse and to the async-exception and fiber code; see Thread.new: let finished threads be collected (DLR ThreadLocal, Thread.list registry) #208.
- Addressed in part by Thread.new: let finished threads be collected (DLR ThreadLocal, Thread.list registry) #208 (merged): the
- Issue #89 leftovers: EUC-KR table gaps, #92 regression tests, cheaper Thread.new location #184: most of it was not the OS thread.
Blocked by #84 (in files that PR changes)
-
Encoding.find(~11× CRuby) andString#encode("ISO-8859-1")(~8×) spend their time inRubyContext.GetRubyEncoding/GetEncodingByRubyName. Caching name →RubyEncodingthere would fix it. Addressed by Fix the cheap performance gaps from #89 (Hash, Array, Enumerable, String, Range, Encoding, Marshal, Digest, Integer) #95. -
Struct.newand class creation spend time in: (addressed by #89: faster class creation, Integer/Range step and first/last, expand_path, pack, reflection paths #182, see Class creation above)RubyContext.CreateClassandRubyClass/RubyModule.AddDependentClass;- the class-hierarchy lock taken in
SetMethodNoEvent.Monitor.EnterinsideRubyContext.ClassHierarchyLockershows up unusually heavy even with no other thread holding it.
-
File.expand_pathis ~2.4× CRuby. The slow part is inRubyUtils.cs. Addressed by #89: faster class creation, Integer/Range step and first/last, expand_path, pack, reflection paths #182: the current directory (agetcwdper call, two for a relative path) is only read for a relative path with no base.File.expand_path("/usr/lib")~2.1 µs → 0.47 µs (CRuby 0.48),("a/b")5.3–7.8 → 3.0 µs (CRuby 2.75). -
instance_variable_get,dup,clone,respond_to?,sendandinspectare 1.4–2.3× CRuby. Those paths live inKernelOps.csandRubyUtils.cs. Addressed by #89: faster class creation, Integer/Range step and first/last, expand_path, pack, reflection paths #182: ivar names skip the conversion site,public_send(:x)skips the argument array (175 → 52 ns, CRuby 105),Kernel#clone(freeze:)is C# (406–438 → 250 ns, CRuby 206).respond_to?,send,dupandinspectalready measured at or below CRuby. - New C# regression tests need registering in
Src/IronRuby.Tests/RubyTests.cs. Addressed by Issue #89 leftovers: EUC-KR table gaps, #92 regression tests, cheaper Thread.new location #184 (StringIO_GetcInvalidBytes1,Digest_OneShot1). StringIO#getc reads one character in C# (and fixes invalid-byte splitting); cached method arity; one-shot Digest hashing #92 has evidence from differential scripts only (StringIOgetcon invalid bytes, Digest), with no IronRuby.Tests case.
Activity
Enumerable#tally/#group_by, sort_by, String#count/delete/squeeze, Mar…
Digest: stream into IncrementalHash; Integer.sqrt/pow/digits/fdiv in …
Merge pull request #95 from Largo/claude/practical-knuth-2u0lhm
Range#first/#last/#include?/#step and Integer#step: Integer fast paths (
Calls: stop allocating a box per Integer argument and per JIT Integer…
Light method frames: no RubyMethodScope for a body that never needs one
Light method frames: take instance variables and constant reads too
Optional positionals before keywords: no splat, and the method JIT ta…
JIT: keyword calls that leave optional positionals out go direct (#89)
Range#min, #max, #include?, #member? in C# (#89)
Range#include? of one-character ASCII String endpoints in C# (#89)
Integer#** answers in C#; rational.rb only gets what makes a Rational…
Rational in C#: a RubyRational type, its arithmetic and Kernel#Ration…
Complex in C#: a RubyComplex type, its arithmetic and Kernel#Complex;…
Instance variable writes of Ruby subclasses of built-in classes take …
18 remaining items
Integer#digits: do not square a radix past the number (#89)
pack('U'): write the code point that was range-checked (#89)
Merge pull request #191 from Largo/claude/issue-89-tos-range
Merge pull request #192 from Largo/claude/issue-89-raise-ensure
Merge pull request #195 from Largo/claude/issue-89-string-slices
Merge pull request #194 from Largo/claude/issue-89-rescue-filter
Release 4.0.4 notes: #89 gaps narrowed, not all closed; list the ones…
Integer() and Float() with exception: go past the keyword Hash from a…
Integer#[offset, size] on a Bignum reads small slices from its bytes
String#to_c's scanner works on the string's characters and a stack bu…
Largo commentedon Nov 11, 2026
GC cost, investigated 2026-11-11 (net11.0 Release; no PR, nothing to fix in IronRuby's GC setup).
s + "x"on 100 KB strings were gen-2 background GCs. A Ruby string is UTF-16 here, so a 100 KB string is a 200 KBchar[]on the large-object heap, and large-object allocation triggers gen-2. A plain .NET program with a comparable live heap (IronRuby's is ~15 MB after startup) pays the same, 33–60 µs per op.RubyMethodBody._astkeeps all prelude ASTs; ruby4.rb's source is held twice). Process-wide knobs (GCLOHThreshold~4× ons + "x", a bigger gen-0 budget −7–10% in a hash loop) would need data across workloads first.Merge pull request #206 from Largo/claude/issue-89-numerics
Merge pull request #210 from Largo/claude/issue-89-raise
Largo commentedon Nov 12, 2026
Closing as completed. Every PR this issue still calls "open" has merged (#202, #206, #207, and before them #186, #191, #195, #208, #210).
Four boxes stay unticked on purpose: long-string
+/hash, the numerics list,raise/rescueandThread.new.joinare still slower than CRuby. In each, what is left is the .NET runtime (large-object-heap allocation and GC, exception dispatch, thread creation,BigIntegeragainst GMP) or needs a design change, not a missed optimization in IronRuby's code.Carried forward:
ensureclauses that still catch and rethrow), with their numbers.ungetc("\r")with universal newlines, unassigned GB18030 four-byte sequences).Generated by Claude Code