jnewland

Where's the bloat: Tracking 'require' memory usage in Ruby and Rails

Among the other awesome things that Ruby Enterprise Edition’s inclusion of the RailsBench GC patch provides is the addition of the allocated_size method on Ruby’s GC constant.

Eric Lindvall recently devised a very clever use for this GC.allocated_size method:

If I wanted to see what was contributing to the large memory footprint of an application on startup, tracking how much memory was allocated during each require would give me a good place to start.

Given the size of GC.allocated_size before and after require calls, we can determine the initial memory profile of any ruby gem, library, file, or Rails model.

To use this to determine the initial memory profile of a beefy Rails application, you’ll first want to download his require_tracking hax. Then, load your production Rails application’s environment with require_tracking turned on:



RAILS_ENV=production ruby -r/tmp/require_tracking.rb  -e "require 'config/environment'"

Memory used by file:

                                     File KB

                            ------------- --------

                      config/environment: 209,623

/srv/myapp/releases/20091230003757/app/models/user: 73,653

/srv/myapp/releases/20091230003757/app/models/store: 70,962

                           ./config/boot: 15,021

/srv/myapp/releases/20091230003757/app/models/discount_code: 9,813

/srv/myapp/releases/20091230003757/app/models/order: 9,390

./config/../vendor/rails/railties/lib/initializer: 9,348

...

71.9 M used by the User model? Holy wow! I know what I’ll be doing today….