Skip to content

Use an always-frozen RubyRegexp subclass for internal Regexps - #10223

Draft
zev wants to merge 1 commit into
jruby:ruby-4.1from
zev:regexp-frozen-subclass
Draft

zev wants to merge 1 commit into
jruby:ruby-4.1from
zev:regexp-frozen-subclass

Conversation

@zev

@zev zev commented Dec 6, 2026

Copy link
Copy Markdown
Contributor

Follow-up to #10128, from @headius' review there: "A future PR could follow RubyString's example and introduce an always-frozen RubyRegexp subclass that will always be used for 'natural' frozen Regexp instances."

What this does

Adds RubyRegexp.FrozenRegexp, a package-private subclass whose isFrozen() always returns true and whose setFrozen() does nothing, like RubyString.DebugFrozenString.

The Regexps that JRuby makes itself now use it:

  • literals and dynamic literals (newRegexp, newRegexpParser, newDRegexp), and $; set by -F
  • newRegexp(Ruby, ByteList), used by Date's parser. These Regexps were not frozen before; Ruby code never sees them.
  • newRegexpFromStr (rb_reg_new_str): a String pattern given to String#split, #match or #match?
  • MatchData#regexp, for example after sub, gsub or scan with a String pattern

regexpInitialize raises FrozenError on a frozen receiver, so I split it: initializePattern does the work after the checks, and FrozenRegexp calls it directly. The encoding check from regexpInitializeString moved into encodingForString, so newRegexpFromStr can use it before the object exists.

Still plain RubyRegexp (frozen by the flag)

  • Regexp.new, #dup, #clone, Regexp.union and Marshal.load. They allocate through Regexp.allocate and then initialize, and the allocated object must not be frozen before initialize runs. As in Freeze all instances of Regexp, except subclass instances #10128, regexpInitialize freezes it when its class is Regexp. Using FrozenRegexp for Regexp.new would mean skipping allocate/initialize when the receiver is Regexp, which breaks a redefined Regexp#initialize, so I didn't.
  • Subclass instances, which stay unfrozen.

No behavior change visible from Ruby: every kind of Regexp has the same frozen state as on ruby-4.1, and as in CRuby 4.1.0-dev.

Testing

  • New TestRubyRegexp (in org/jruby/test, so surefire runs it): Regexps that JRuby makes stay frozen after setFrozen(false), and a Regexp made from a String pattern is == to Regexp.new of that pattern. The first test fails on ruby-4.1.

On this branch and on ruby-4.1 (a3434dd), with the same results:

  • mspec ci on core/regexp, core/matchdata, core/marshal, core/string, core/kernel, language/regexp, library/date: 1 failure interpreted (Kernel#require with a c-extension file). With -X+C there are 5, all also on ruby-4.1, including MatchData#regexp returns the same Regexp used to match.
  • test/mri test_regexp, test_marshal, test_string, test_symbol, test_enum, test_m17n, test_frozen with the excludes, interpreted and -X+C: 0 failures.

Not in this PR

  • The FrozenError message for a frozen Regexp that isn't a literal, for example r = /q/; def r.foo; end, is can't modify frozen Object: /q/: /q/ (CRuby: can't modify frozen Regexp: /q/). This was noted in Freeze all instances of Regexp, except subclass instances #10128: RubyBasicObject#testFrozen passes "Object: " + inspect as the type name.
  • With -X+C, MatchData#regexp returns a new Regexp instead of the one used to match. I'll look at that in a separate PR.
  • RubyDate.newRegexpFromCache (public RubyRegexp(Ruby, Regex, ByteList, RegexpOptions) constructor) and newDummyRegexp (Complex/Rational parsing) still make unfrozen Regexps. Both are internal.
  • TestRegexpCache is in org/jruby, which surefire's includes don't cover, so it never runs.

🤖 Generated with Claude Code

Regexps that JRuby makes itself (literals, dynamic literals, Regexps
built from a String pattern, Date's parse patterns and MatchData#regexp)
are now instances of RubyRegexp.FrozenRegexp, whose isFrozen() is always
true and whose setFrozen() does nothing, following RubyString's frozen
subclasses. Regexp.new, dup, clone and Marshal.load still allocate a
plain RubyRegexp and freeze it in regexpInitialize.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@kares

kares commented Dec 6, 2026

Copy link
Copy Markdown
Member

@headius does this actually make sense these days?
thought it's better to keep (regexp) sites mono-morphic, as far as Java JIT is concerned, than having unnecessary sub-classes...

@zev

zev commented Dec 6, 2026 •

Copy link
Copy Markdown
Contributor Author

@kares good question, so I measured it. Short version: you're right, and the cost is in a different place than regexp call sites.

What changes for the JIT

FrozenRegexp overrides only isFrozen() and setFrozen(), so every other RubyRegexp method still has one implementation and calls through a RubyRegexp-typed receiver stay devirtualized. Call sites that see regexps now see two Java classes, RubyRegexp (Regexp.new, dup, clone, union, Marshal.load) and FrozenRegexp (literals and the rest). In C2's inlining log those sites go bimorphic and are still inlined (determineSplitPattern, getMetaClass, frozen_p).

The larger effect is on RubyBasicObject#isFrozen(). RubyString.DebugFrozenString also overrides it, but outside debug mode it is loaded and never instantiated, and C2's class hierarchy analysis ignores classes with no instances. So on ruby-4.1 isFrozen() is a direct call everywhere. Literals create FrozenRegexp instances at boot, so with this PR isFrozen() has two live implementations for every object. With -XX:+PrintInlining on Temurin 21, RubyBasicObject::isFrozen is "no static binding" at 0 call sites on ruby-4.1 and at 7 call sites with this PR, including testFrozen, ensureInstanceVariablesSettable, Kernel#frozen? and singletonClass. On a call site that sees many classes, that turns the inlined flag test into a virtual call.

Numbers

ruby-4.1 (a3434dd) against this PR (a9e02fd), Apple M4 Pro, one JVM per case, 5 forks interleaved. Each fork runs 8 rounds of 2 s; the first 4 are warmup. A fork's score is its best steady round, and each table shows the median of the 5 forks' scores. Higher is better.

Regexp workload: passes per second through run_once in bench_regexp_poly.rb. One pass is 472 Regexp operations: 8 Regexps × 9 strings × 6 ops (match?, ===, =~, sub, split, case/when), plus 5 per Regexp (Hash lookup, Array#include?, eql?, frozen?, hash).

JDK Regexps used ruby-4.1 (passes/s) PR (passes/s) PR / base
Temurin 21 8 literals 57,319 56,759 0.99
Temurin 21 4 literals + 4 from Regexp.new/union 58,038 57,671 0.99
Temurin 25 8 literals 59,552 58,888 0.99
Temurin 25 4 literals + 4 from Regexp.new/union 59,737 59,685 1.00

Mutation workload, no Regexps: passes per second through run_once in bench_frozen_check.rb. One pass is 16 objects of 4 classes writing ivars, then 50 × (Array#<<, Hash#[]=, String#<<, a Struct setter, frozen?). All of these check frozen state before writing.

JDK ruby-4.1 (passes/s) PR (passes/s) PR / base
Temurin 21 391,011 371,552 0.95
Temurin 25 467,971 462,005 0.99

The 0.95 on Temurin 21 is a weak signal because the fork ranges overlap (375k–432k against 355k–422k), but it points the same way as the inlining log.

What the subclass buys

On ruby-4.1, every Regexp instance is already frozen with the flag bit: regexpInitialize freezes it when its class is Regexp, and MatchData#regexp calls setFrozen(true). That covers literals, Regexp.new, dup, clone, union, Marshal.load and String patterns. Ruby code can't clear the flag. The PR adds two things only: the internal newRegexp(Ruby, ByteList) Regexps used by Date's parser become frozen, and Java code can't call setFrozen(false) on a natural Regexp.

So the subclass adds JIT polymorphism for every object in exchange for no behavior change visible from Ruby.

Offer

@headius since this came from your #10128 review idea, which would you prefer?

  1. Close this PR.
  2. Reduce it to setFrozen(true) in newRegexp(Ruby, ByteList), with no subclass, plus the TestRubyRegexp test. The test also fixes a gap: the existing TestRegexpCache is in org/jruby, outside surefire's includes, so it never runs.
  3. Keep the subclass if there's a reason I'm missing. I can run the same benchmarks on GraalVM or OpenJ9 if that would help.
Benchmark scripts

bench_regexp_poly.rb (run as jruby bench_regexp_poly.rb literal|mixed 2 8):

# Regexp Java-class polymorphism benchmark (jruby#10223).
# Usage: jruby bench_regexp_poly.rb literal|mixed [seconds_per_round] [rounds]
#   literal: every Regexp is a literal (FrozenRegexp on the PR branch, RubyRegexp on base)
#   mixed:   half literals, half Regexp.new/union/dup (two Java classes on the PR branch, one on base)
mode = ARGV[0] or abort "mode?"
secs = (ARGV[1] || 2.0).to_f
rounds = (ARGV[2] || 8).to_i

LITERALS = [/foo\d+/, /bar(baz)?/, /\Aqux/, /z{2,}/, /[aeiou]{3}/, /end\z/, /x.y/, /hello|world/]
SOURCES  = LITERALS.map(&:source)

REGEXPS = case mode
when "literal" then LITERALS
when "mixed"
  # alternate: literal, Regexp.new, literal, union, literal, dup ...
  LITERALS.each_with_index.map do |re, i|
    case i % 4
    when 0, 2 then re
    when 1 then Regexp.new(SOURCES[i])
    when 3 then Regexp.union(Regexp.new(SOURCES[i]))
    end
  end
else abort "bad mode #{mode}"
end

STRS = ["foo123", "barbaz", "quxly", "zzzz", "aeiou", "the end", "xzy", "hello there", "nomatch"]
HASH = REGEXPS.each_with_index.to_h
ARR  = REGEXPS.dup

def run_once(regexps, strs, hash, arr)
  acc = 0
  regexps.each do |re|
    strs.each do |s|
      acc += 1 if re.match?(s)
      acc += 1 if re === s
      acc += 1 if s =~ re
      acc += s.sub(re, "-").bytesize
      acc += s.split(re).size
      case s
      when re then acc += 1
      end
    end
    acc += hash[re]
    acc += 1 if arr.include?(re)
    acc += 1 if re.eql?(regexps[0])
    acc += 1 if re.frozen?
    acc += re.hash & 1
  end
  acc
end

results = []
rounds.times do |r|
  n = 0
  t0 = Process.clock_gettime(Process::CLOCK_MONOTONIC)
  deadline = t0 + secs
  while Process.clock_gettime(Process::CLOCK_MONOTONIC) < deadline
    100.times { run_once(REGEXPS, STRS, HASH, ARR) }
    n += 100
  end
  el = Process.clock_gettime(Process::CLOCK_MONOTONIC) - t0
  results << n / el
end
classes = REGEXPS.map { |re| re.to_java.java_class.simple_name rescue "?" }.tally
# drop the first half as warmup
steady = results.drop(rounds / 2)
puts "RESULT mode=#{mode} best=#{steady.max.round(1)} median=#{steady.sort[steady.size / 2].round(1)} rounds=#{results.map { |x| x.round }.inspect} classes=#{classes}"

bench_frozen_check.rb (run as jruby bench_frozen_check.rb 2 8):

# Mutation-heavy, non-Regexp workload: every op goes through RubyBasicObject#isFrozen
# (testFrozen / checkFrozen / ensureInstanceVariablesSettable) on many receiver classes.
# Usage: jruby bench_frozen_check.rb [seconds_per_round] [rounds]
secs = (ARGV[0] || 2.0).to_f
rounds = (ARGV[1] || 8).to_i

class P1; def initialize; @a = 0; end; def bump; @a += 1; end; end
class P2; def initialize; @b = 0; end; def bump; @b += 2; end; end
class P3; def initialize; @c = 0; @d = 1; end; def bump; @c += 1; @d = @c; end; end
class P4 < P1; def bump; @a += 3; @e = 1; end; end
S = Struct.new(:x)

def run_once(objs)
  acc = 0
  objs.each { |o| o.bump }
  a = []
  h = {}
  s = +""
  st = S.new(0)
  50.times do |i|
    a << i
    h[i] = i
    s << "x"
    st.x = i
    acc += 1 if a.frozen?
  end
  a.clear; h.clear
  acc + s.bytesize
end

OBJS = [P1.new, P2.new, P3.new, P4.new] * 4
results = []
rounds.times do
  n = 0
  t0 = Process.clock_gettime(Process::CLOCK_MONOTONIC)
  deadline = t0 + secs
  while Process.clock_gettime(Process::CLOCK_MONOTONIC) < deadline
    100.times { run_once(OBJS) }
    n += 100
  end
  results << n / (Process.clock_gettime(Process::CLOCK_MONOTONIC) - t0)
end
steady = results.drop(rounds / 2)
puts "RESULT mode=frozencheck best=#{steady.max.round(1)} median=#{steady.sort[steady.size / 2].round(1)} rounds=#{results.map(&:round).inspect}"

Inlining check: JAVA_OPTS="-XX:+UnlockDiagnosticVMOptions -XX:+PrintCompilation -XX:+PrintInlining" jruby bench_regexp_poly.rb mixed 2 6 | grep -c 'RubyBasicObject::isFrozen.*no static binding'

🤖 Generated with Claude Code

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants