Today I Learned

hashrocket A Hashrocket project

Count the number of objects in memory

Let's say you're having memory issues in your Ruby app and you want to get a feel for how many objects are instantied. You can use ObjectSpace!

require 'objspace'
ObjectSpace.each_object(Object).count
# in my typical rails app: 394683

Everything is a child of Object (for the most part), so you have about 394683 objects in memory! That's a lot! You can narrow this down if you like to just String.

ObjectSpace.each_object(String).count
# in my typical rails app: 295261

But let's check something more interesting, like TZInfo::CountryTimezone:

ObjectSpace.each_object(TZInfo::CountryTimezone).count
# in my typical rails app: 348

Neat!

See More #ruby TILs
Looking for help? Each developer at Hashrocket has years of experience working with Ruby applications of all types and sizes. We're an active presence at Ruby conferences, have written some of the most popular gems, and have worked on many of the web's Ruby on Rails success stories. Contact us today to talk about your Ruby project.