Garbage collection and memory
GC.stat
GC.stat is a snapshot of the collector: how many objects are alive, how many were allocated in total, how often the collector ran and how much time it used. One key answers most questions:
ruby -e 'puts GC.stat[:heap_live_slots]'
23883
A bare Ruby already holds thousands of objects, so the number alone means little. Read it twice and look at the difference, which is the memory the work actually kept. The number also moves from one process to the next: the figure above is one real run, and a second run of the same command prints a close but different one.
Live slots
The same reading before and after allocating a hundred thousand strings. A GC.start on each side forces a collection, so the gap is what the work keeps, not what the heap happens to hold:
GC.start before = GC.stat[:heap_live_slots] strings = Array.new(100_000) { "x" * 10 } GC.start after = GC.stat[:heap_live_slots] puts "strings: #{strings.size}" puts "live slots for the array and its strings: #{after - before}"
ruby gc.rb
strings: 100000
live slots for the array and its strings: 100007
The difference is about a hundred thousand slots, which is the array plus one string per entry. A loop that builds the strings and throws them away leaves the live count flat but raises total_allocated_objects, and that is the number that predicts a collection pause.
ObjectSpace
ObjectSpace.count_objects breaks the heap down by type, and ObjectSpace.each_object(String) walks the strings that are still alive. A string-heavy program shows it at once:
GC.start before = ObjectSpace.each_object(String).count messages = Array.new(1_000) { |i| "row #{i}" } GC.start after = ObjectSpace.each_object(String).count puts "messages: #{messages.size}" puts "strings still live: #{after - before}"
ruby gc.rb
messages: 1000
strings still live: 1000
A thousand rows, a thousand live strings. The collector also counts what the same loop handed to it:
GC.start before = GC.stat[:total_allocated_objects] messages = Array.new(1_000) { |i| "row #{i}" } after = GC.stat[:total_allocated_objects] puts "messages: #{messages.size}" puts "objects allocated: #{after - before}"
ruby gc.rb
messages: 1000
objects allocated: 1996
Nearly half of the allocations in this tiny script are strings. A real application that builds a message per request allocates a dozen strings it never shows anyone; the fix is usually to build the message only when the level is enabled.
The strings that dominate
Three patterns account for most avoidable string churn:
- Interpolation in a loop. "id=#{id}" in a loop over a million rows allocates a million strings. Build it once outside, or write to an IO.
- Concatenation with +. out += line copies the whole string each time and is quadratic. out << line appends, and the benchmark in the next lesson shows the difference.
- A frozen literal that is not frozen. A string literal in a method called in a loop allocates per call unless the file has the frozen_string_literal comment.
What to watch for
A high live count is not a leak. A leak is a count that climbs with every
request and never comes down; a high constant is a cache or a big
configuration. Compare two requests, not two minutes.
GC.start before a measurement forces a collection
and makes the number repeatable. It also hides the cost the production
process pays, so use it for a measurement and not in the code.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does
GC.stat[:heap_live_slots]count?Answer
The objects the collector is holding as live at this moment
Live slots are the objects alive right now; the total ever allocated is a different key and only grows.
-
What does this program print?
before = GC.stat[:count] GC.start after = GC.stat[:count] puts after - beforeAnswer
1
GC.start runs a collection at once, so the counter of collections goes up by exactly one.
-
What does
GC.stat[:total_allocated_objects]count?Answer
Every object allocated since the process started, the freed ones included
The counter only grows: it is the work handed to the collector, which is what predicts a pause.
-
What does this program print?
cache = {} GC.start before = GC.stat[:heap_live_slots] 1_000.times { |i| cache[i] = "v" } GC.start after = GC.stat[:heap_live_slots] puts cache.size puts after - before > 1_000Answer
1000 / true
The hash keeps a thousand entries plus the strings it stores, so the live count grows by more than a thousand and the comparison is true.
-
What does this program print?
def label "row" end GC.start before = GC.stat[:total_allocated_objects] 1_000.times { label } after = GC.stat[:total_allocated_objects] puts after - beforeAnswer
1004
A file without the frozen_string_literal comment allocates a new string on every call, and the loop adds a few objects of its own.
-
What does this program print?
GC.start before = GC.stat[:total_allocated_objects] out = +"" 100.times { |i| out = out + i.to_s } after = GC.stat[:total_allocated_objects] puts out.size puts after - beforeAnswer
190 / 206
Each step allocates the string from to_s and the combined string + returns, so a hundred appends cost about two hundred objects, while the final size is 190 characters.
-
What does
GC.startbefore a measurement do?Answer
It forces a collection, so a live count is repeatable, but it hides the pause the production process pays
A collection first makes the live number stable, and it is exactly the cost a measurement should not quietly remove from the picture.
-
Which reading is the sign of a memory leak?
Answer
A live count that climbs with every request and never comes back down
A leak is growth that never returns to a baseline; a high constant is a cache or a big configuration.
-
What does
ObjectSpacegive a memory question?Answer
A breakdown of the heap by object type, and a walk over the live objects of one class
count_objects shows which types fill the heap and each_object walks the live instances, which is how string churn is found.
-
How many objects does
"id=#{n}"allocate whennis an Integer?Answer
Two, the string the interpolation builds and the string to_s returned for the number
Interpolation calls to_s on the value, so a number adds a temporary string to every iteration, which is why the allocation count doubles.
Article author: Arthur Isaev