10

Is there any function in ruby, to find memory used by ruby object.
Similar to how C has the sizeof() function and PHP has the memory_get_usage() function. Does ruby have an equivalent function/method?

rudolph9
  • 8,021
  • 9
  • 50
  • 80
Sandip Karanjekar
  • 850
  • 1
  • 6
  • 23
  • 4
    Probably a duplicate: http://stackoverflow.com/questions/3973094/how-to-measure-the-size-of-a-ruby-object – Matt Dec 10 '12 at 13:39
  • 1
    I'm curious: what is the purpose of your question? Do you want to be able to know the size of an object or are you trying to figure out how much memory have a large number of certain objects will take? – Sim Dec 23 '12 at 01:30
  • This should be useful: https://gist.github.com/camertron/2939093 – Craig Treptow Jan 13 '14 at 16:29
  • This question is a duplicate. See: http://stackoverflow.com/questions/3973094/how-to-measure-the-size-of-a-ruby-object – fred271828 Mar 04 '14 at 22:19

2 Answers2

8

ObjectSpace#memsize_of from the Ruby docs:

Return consuming memory size of obj.

[1] pry(main)> require 'objspace'
=> true
[2] pry(main)> ObjectSpace.memsize_of('')
=> 40
[3] pry(main)> ObjectSpace.memsize_of([])
=> 40
[4] pry(main)> ObjectSpace.memsize_of(1..100)
=> 40
[5] pry(main)> ObjectSpace.memsize_of('X' * 100)
=> 141
[6] pry(main)> ObjectSpace.memsize_of(('X' * 100).chars)
=> 840
sheldonh
  • 2,684
  • 24
  • 31
Travis
  • 13,311
  • 4
  • 26
  • 40
2

This is a stretch, but if your goal is to look for a memory leak, rather than see the size of individual objects, you might look at object_count(cls), as in:

>> ObjectSpace.each_object(Object).count
=> 114629
>> ObjectSpace.each_object(Array).count
=> 10209

etc. FWIW, symbols are a little different: you can get the count of symbols via:

>> Symbol.all_symbols.count
=> 17878

To find out if you have a leak of not, you can manually call GC, count your objects, run your code for a while, call GC again, then see if any object count has grown significantly.

Of course, this doesn't tell you the size of each object, just how many of each class are allocated.

There's also memprof, but I admit that I haven't used that yet.

fearless_fool
  • 33,645
  • 23
  • 135
  • 217
  • 3
    This is the number of objects in memory. The original question, as I understand it, asks how to find out the memory usage (in bytes) of a single object. – Ariejan Jun 23 '14 at 07:58
  • @Ariejan: Fully agree. That's why I said "*if* your goal is to look for a memory leak, rather than see the size of individual objects..." – fearless_fool Jun 23 '14 at 22:20