0Pricing
Ruby Academy · Lesson

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_objects grows 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

  1. Measuring Performance
  2. Profiling Tools
  3. Memory Optimization
  4. Common Bottlenecks
← Back to Ruby Academy