Reputation: 850
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?
Upvotes: 11
Views: 8182
Reputation: 14436
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
Upvotes: 9
Reputation: 35159
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.
Upvotes: 2