How to measure the size of a Ruby object?

martini-bonanza picture martini-bonanza · Oct 19, 2010 · Viewed 12.1k times · Source

I'm having Memcache problems and I was wondering what is the best way to know how big the objects I create are.

The only solution I have is to put them into Memcache which display their size in bytes (by the way, can I customize Memcache's output? I want readable kilobytes…).

Thank you,

Kevin

Answer

Michael Kohl picture Michael Kohl · Oct 20, 2010

The excellent Eigenclass blog had an interesting article on that once:

http://web.archive.org/web/20120126022146/http://eigenclass.org/R2/writings/object-size-ruby-ocaml

There also was a good discussion on ruby-talk, which led to some code by Robert Klemme (Ruby Best Practices):

http://www.ruby-forum.com/topic/156648

http://www.pastie.org/217131

Plugging the values from the first article into the script might get you started and is probably quite educational.

You could also check out memprof, though it's more about object references and finding memory leaks than actual sizes:

http://github.com/ice799/memprof