Skip to content

Performance gaps found while optimizing 2016-era code (not yet addressed) #89

Closed

Description

@Largo

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.Create cloned 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, +, strip and hash on ~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#read of 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, taskset to one core, warm-up, best of 5, two interleaved runs): s.dup 0.26 / 0.19 µs (CRuby 0.06), String.new(s) 0.10 / 0.09 µs (CRuby 0.15), whole-buffer StringIO#read of 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), strip with a leading blank 58 / 50 µs (CRuby 0.1: it shares the tail, IronRuby's content has no offset), rstrip 0.38 / 0.34 µs (CRuby 0.07), hash 76 / 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:
        • strip with 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 µs
        • s[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 µs
        • hash of 100 KB: 75–85 / 75–92 → 40–45 / 41–45 µs (CRuby 24)
        • strip.hash: 115 → 45 µs
        • strip =~ /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: with DOTNET_GCLOHThreshold=0x200000 it 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).hash 2.3–3.0 / 1.9–2.3 → 1.1–1.6 / 1.0–1.5 µs (CRuby 0.34–0.43). 2.44M eql? 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. XxHash3 was not taken (a NuGet dependency, and no claim to resist flooding).
        • 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), strip with 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").hash 107–131 → 68–78 (CRuby 50); bytesize 68–79 → 33–42; =~ unchanged (117–158 → 139–144, CRuby 67). What is left of s + "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-ASCII hash held 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.
  • Fresh string literals are slow to create and to read as bytes.
  • String#sum (MutableStringOps.GetChecksum) catches OverflowException on its normal path. Addressed by Fix the cheap performance gaps from #89 (Hash, Array, Enumerable, String, Range, Encoding, Marshal, Digest, Integer) #95.
  • String#count, #delete and #squeeze are 30–145× slower than CRuby in a survey benchmark, and String#ljust/center with long results is still ~4×.
  • StringContent.ContainsInvalidCharacters allocates 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.new and 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 Regex cache 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.new went from ~6.5 µs to 0.33 µs (CRuby 4.1), and an interpolated literal from ~3 µs to 0.48 µs.
  • $~.string.class for a String subclass is String; 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.glob is still ~5–8× slower than CRuby after MatchData shares the subject's immutable string; fnmatch patterns translated once #90. Part of the cost is a FileExists/DirectoryExists check per matched entry. Skipping that check would change how broken symlinks are handled.

IO

Collections and iteration

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#step 1.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 and Integer("123") 150 → 75–88 ns (CRuby 30 / 53). Range#include?, to_c and round(-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.sqrt and Integer#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 fixes 5[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), and 0.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 slow tail. call into library methods of more than six parameters). digits already ~1.2× CRuby (312 vs 250 ns).
    • Kernel#Float/Integer and Integer#step;
    • Range#size, step, first, last and include?;
    • fdiv, to_c, and Integer#round with 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) and digits (953 → 354 ns).
      • fdiv: has Fixnum overloads (403 → 35 ns).
      • Fixnum **: computes in a long.
      • Prelude fast paths: Integer#[] (357 → 211 ns), Float() (~1000 → ~400 ns) and Range#size (593 → 303 ns).
      • Still open: Kernel#Integer/#Float, where the keyword-argument Ruby wrapper call is most of the cost; Integer#** behind rational.rb's wrapper; Integer#step; Range#step/first/last/include?; to_c; and round with a negative digit count.
    • 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 while loop, IronRuby's ~1 ns:
      • At or below CRuby: Float("1.5") 121 / 111 ns (99), Float("1_000.5") 139 / 118 (137), Float #step and Range#step over Floats 0.5–0.6×, Integer#step(by:, to:) and Range#step 0.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-digit Integer() (0.8–1.0×).
      • Within ~2×: x[3] 37 / 38 ns (26), Integer(12) 43 / 40 (31), 3 ** 5 62 / 53 (36), 3.to_c 106 / 78 (58), 3 ** -2 128 / 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_c 373 / 334 (173).
      • Still open: Range#size 350 / 271 ns against 47 (~6–7×; the prelude method makes ~8 dynamic calls, and is_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×) and Integer.sqrt(2**2000 + 1) 17.6 / 12.0 µs against 5.5 (BigInteger Newton iteration, slow division on net8.0).
      • Integer.sqrt is addressed by Integer.sqrt: Karatsuba square root; String#hash: SipHash-1-3 for long ASCII strings #202 (open): exact UInt128 arithmetic from the double's root for 262..2106, Zimmermann's Karatsuba square root (MCA algorithm 1.12, GMP's mpz_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#size is 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).size 330-360 / 300 → 70-77 / 63-70 ns, (1...10).size 343-393 / 297-310 → 70-73 / 67-73, (1..).size 333-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) and Float("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_c 2310–2470 / 2155 → 2025–2260 / 1923 (1540), scanner without its copies. Also fixed there: Float(x, exception: true)'s warning line (198) and Integer("", 1) (invalid radix). Left: x[3], Integer(12), 3 ** 5, 3 ** -2, 3.to_c, Range#size and is_a?/=== are already C# with instruction counts near CRuby's (3 ** 5 440 vs 412, 3 ** -2 754 vs 796, 3.to_c 666 vs 650, (1..10).size 437 vs 459); their time gap is the general cost of a dynamic call and an allocation.
  • 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.
  • IronRuby's own Integer#to_s is 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.ToRadixString could hand values above ~1k bits to the patched MathUtils.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 keeps BigInteger.ToString below 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 %b of Bignums (once per digit; 100k bits 3.1 s → 23 / 8 ms, CRuby 1.3) and Integer#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.
  • 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, via clock_gettime on Unix and GetThreadTimes on 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**31 raises RangeError, 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.0 1 << 2**31 builds 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.load of 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 match ruby_strtod.

Libraries

  • Streaming Digest is quadratic. Digest#update keeps the whole input in memory, and digest after each update copies it. Incremental hashing that can be cloned would fix it.
  • StringIO getc on Big5/EUC-KR differs from CRuby where IronRuby's valid_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 and chars/length/inspect threw. 16 sequences → 0 differing, and 122 → 0 in 3 × 4,800 random strings.
    • Left: scrub of 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.

Exceptions and class creation

  • raise/rescue is ~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/catch one or two. What is left (~25 µs here) is .NET 8's native exception dispatch itself: a failing System::Int32.Parse costs 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 StackTrace capture for the backtrace.
    • throw/catch is ~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 a rescue that 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, because Interpreter.Run runs finally blocks from a catch. The way out is a real CLR filter plus a finally for ensure-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 with ensure 395 / 149 (732 / 354), CRuby 2.8; through 20 frames with a non-matching rescue 400 / 160 (670 / 524), CRuby 4.1; the same plus e.backtrace 184 / 114, CRuby 21; throw through 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.CaptureTrace takes a System.Diagnostics.StackTrace of the whole stack at the catch site on every raise (DebugStackTrace::GetStackFramesInternal is ~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, msg and to raise "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 a when filter on the catch tag did not measurably help.
  • 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.new 120–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.
  • Thread.new.join is ~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.new built the caller's whole backtrace to record its file: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 CLR StackTrace capture 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 { }.join 51 / 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's ThreadStore::RemoveThread (cleaning up dead threads, a walk of the thread list), plus ThreadStore::GetThreadList and 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 RemoveThread cost came from finished threads that stayed reachable. The DLR's ThreadLocal<InterpretedFrame> held each entry's Thread (new DLR patch 0108 holds a per-thread token instead), and Thread.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 Ruby Thread is its System.Threading.Thread, so pooling needs a separate identity object and changes to every Thread.CurrentThread use and to the async-exception and fiber code; see Thread.new: let finished threads be collected (DLR ThreadLocal, Thread.list registry) #208.

Blocked by #84 (in files that PR changes)

Activity

  1. 18 remaining items

  2. Largo commented on Nov 11, 2026

    @Largo
    OwnerAuthor

    GC cost, investigated 2026-11-11 (net11.0 Release; no PR, nothing to fix in IronRuby's GC setup).

    • The "~0.85 ms gen-0 GC" seen behind 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 KB char[] 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.
    • Real gen-0 pauses are ~3× a bare app's (0.3–0.45 ms vs 0.15 ms traced), ~70% of it scanning thread stacks: a Ruby-level call is ~10 CLR frames, several with large GC info. Card marking, handles (no leak; ~3k handles, 363 dependent) and survivors are small.
    • IronRuby sets no GC options (default workstation + concurrent).
    • Options, none applied: hold string contents as bytes (halves large-object churn), fewer CLR frames per Ruby call, a smaller startup heap (expression trees kept by not-yet-compiled interpreted lambdas are ~25% of its objects; RubyMethodBody._ast keeps all prelude ASTs; ruby4.rb's source is held twice). Process-wide knobs (GCLOHThreshold ~4× on s + "x", a bigger gen-0 budget −7–10% in a hash loop) would need data across workloads first.
  3. added 2 commits that reference this issue on Nov 11, 2026
  4. Largo commented on Nov 12, 2026

    @Largo
    OwnerAuthor

    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/rescue and Thread.new.join are still slower than CRuby. In each, what is left is the .NET runtime (large-object-heap allocation and GC, exception dispatch, thread creation, BigInteger against GMP) or needs a design change, not a missed optimization in IronRuby's code.

    Carried forward:


    Generated by Claude Code

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions