Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

135
Views
How Ruby GC count allocated RegularExpression

Today i learned about Ruby Garbage Collection, and do some test

def count_allocated_objects
  before = GC.stat(:total_allocated_objects)

  yield

  after = GC.stat(:total_allocated_objects)

  after - before
end

count_allocated_objects {
  s = "this is a string"
  r = /[a-z]/
} # => 1, so only the string `s` be counted

count_allocated_objects {
  s = "this is a string"
  s.gsub(/[a-z]/, "")
} # => 6, in this case, is the regex `/[a-z]/` counted ?

As you can see, it looks like the regex /[a-z]/ is not counted by the GC. is it the Ruby's rule or the GC's stat total_allocated_objects rule ?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Turn out the Regex is considered as frozen object (similar to the frozen String) and the GC will not count those frozen objects, so the Regex will not be counted. (regardless which Ruby version, at least so far)

count_allocated_objects {
  s1 = "this is a string"
  s2 = "another string"
  r = /[a-z]/
} # ruby 2.6.5 => 2, ruby 3.0.0 => 2, ruby 3.1.0 => 3

although ruby 3.1.0 return 3, but if i remove r from the above code, it still return 3

count_allocated_objects {
  s1 = "this is a string"
  s2 = "another string"
} # ruby 2.6.5 => 2, ruby 3.0.0 => 2, ruby 3.1.0 => 3

test with a frozen String

count_allocated_objects {
  s1 = "this is a string"
  s2 = "another string".freeze
} # ruby 2.6.5 => 1, ruby 3.0.0 => 1, ruby 3.1.0 => 2

For sure i checked a frozen String and Regexp in heap dump

require 'objspace'
ObjectSpace.trace_object_allocations_start

s1 = "this is a string"
s2 = "another string".freeze
r = /[a-z]/

p r.frozen? # true
p ObjectSpace.dump(r) # "{..\"type\":\"REGEXP\", ... \"frozen\":true ...
p ObjectSpace.dump(s2) # "{..\"type\":\"STRING\", ... \"frozen\":true ...
p ObjectSpace.dump(s1) # didn't contain \"frozen\"
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!