Repository navigation
Conversation
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>
|
@headius does this actually make sense these days? |
|
@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
The larger effect is on Numbers
Regexp workload: passes per second through
Mutation workload, no Regexps: passes per second through
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 buysOn 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?
Benchmark scripts
# 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}"
# 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: 🤖 Generated with Claude Code |
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 whoseisFrozen()always returnstrueand whosesetFrozen()does nothing, likeRubyString.DebugFrozenString.The Regexps that JRuby makes itself now use it:
newRegexp,newRegexpParser,newDRegexp), and$;set by-FnewRegexp(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 toString#split,#matchor#match?MatchData#regexp, for example aftersub,gsuborscanwith a String patternregexpInitializeraisesFrozenErroron a frozen receiver, so I split it:initializePatterndoes the work after the checks, andFrozenRegexpcalls it directly. The encoding check fromregexpInitializeStringmoved intoencodingForString, sonewRegexpFromStrcan use it before the object exists.Still plain
RubyRegexp(frozen by the flag)Regexp.new,#dup,#clone,Regexp.unionandMarshal.load. They allocate throughRegexp.allocateand then initialize, and the allocated object must not be frozen beforeinitializeruns. As in Freeze all instances of Regexp, except subclass instances #10128,regexpInitializefreezes it when its class isRegexp. UsingFrozenRegexpforRegexp.newwould mean skippingallocate/initializewhen the receiver isRegexp, which breaks a redefinedRegexp#initialize, so I didn't.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
TestRubyRegexp(inorg/jruby/test, so surefire runs it): Regexps that JRuby makes stay frozen aftersetFrozen(false), and a Regexp made from a String pattern is==toRegexp.newof that pattern. The first test fails onruby-4.1.On this branch and on
ruby-4.1(a3434dd), with the same results:mspec cioncore/regexp,core/matchdata,core/marshal,core/string,core/kernel,language/regexp,library/date: 1 failure interpreted (Kernel#requirewith a c-extension file). With-X+Cthere are 5, all also onruby-4.1, includingMatchData#regexp returns the same Regexp used to match.test/mritest_regexp,test_marshal,test_string,test_symbol,test_enum,test_m17n,test_frozenwith the excludes, interpreted and-X+C: 0 failures.Not in this PR
FrozenErrormessage for a frozen Regexp that isn't a literal, for exampler = /q/; def r.foo; end, iscan'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#testFrozenpasses"Object: " + inspectas the type name.-X+C,MatchData#regexpreturns a new Regexp instead of the one used to match. I'll look at that in a separate PR.RubyDate.newRegexpFromCache(publicRubyRegexp(Ruby, Regex, ByteList, RegexpOptions)constructor) andnewDummyRegexp(Complex/Rational parsing) still make unfrozen Regexps. Both are internal.TestRegexpCacheis inorg/jruby, which surefire's includes don't cover, so it never runs.🤖 Generated with Claude Code