Memory Optimization
Reduce allocations.
Why Memory Matters
Every object Ruby creates costs memory and adds garbage collection work. Fewer allocations means faster, leaner programs.
- The GC pauses to reclaim objects
- High allocation rates trigger more GC runs
- Reducing allocations is often the biggest win
before = GC.stat(:total_allocated_objects)
100.times { 'new string' + '!' }
after = GC.stat(:total_allocated_objects)
puts "Allocated: #{after - before} objects"Counting Allocations
GC.stat exposes allocation counters you can diff around a block.
:total_allocated_objectsgrows forever- Diff before and after to measure a section
def allocations
before = GC.stat(:total_allocated_objects)
yield
GC.stat(:total_allocated_objects) - before
end
puts allocations { Array.new(1000) { |i| i.to_s } }All lessons in this course
- Measuring Performance
- Profiling Tools
- Memory Optimization
- Common Bottlenecks