Monday, 26 August 2013

Anonymous modules and classes garbage collection in Ruby

Anonymous modules and classes garbage collection in Ruby

I'd like to know why the following code apparently doesn't garbage collect
anonymous modules that are supposedly not referenced anywhere anymore (not
extended/included, not named, containing array set to nil).
I'd appreciate if anyone could clarify what's going on under the hood with
relatively simple/general programming words. Is there a special ruby way
to achieve this ? Can't anonymous modules/classes be garbage collected no
matter what ? Or was i simply mislead by the memory stats i got ?
NOTE : i'm using ruby 1.9.3 ; don't know if ruby 2.x would change anything
at all...
Thanks in advance.
puts("INITIAL OBJECT SPACE OBJECTS : #{ObjectSpace.count_objects}")
i = 100000
ms = []
i.times do
ms << Module.new do
def foo()
puts('foo method called')
end
end
end
puts("#{i} MODULES CREATED")
puts("OBJECT SPACE OBJECTS : #{ObjectSpace.count_objects}")
ms = nil
ObjectSpace.garbage_collect
puts("#{i} MODULES GARBAGE COLLECTED")
puts("WAITING TO END PROGRAM")
stop = gets
puts("FINAL OBJECT SPACE OBJECTS : #{ObjectSpace.count_objects}")
I say "apparently doesn't garbage collect" because my OS task manager
doesn't show any reduction in memory usage from the process, and calling
ObjectSpace.count_objects yields the following, which i read (wrongly so
?) as : no the memory used by your modules has not been freed.
INITIAL OBJECT SPACE OBJECTS : {:TOTAL=>14730, :FREE=>251, :T_OBJECT=>8,
:T_CLASS=>542, :T_MODULE=>21, :T_FLOAT=>7, :T_STRING=>6349, :T_REGEXP=>24,
:T_ARRAY=>1009, :T_HASH=>14, :T_BIGNUM=>3, :T_FILE=>10, :T_DATA=>408,
:T_MATCH=>108, :T_COMPLEX=>1, :T_NODE=>5956, :T_ICLASS=>19}
100000 MODULES CREATED
OBJECT SPACE OBJECTS : {:TOTAL=>311794, :FREE=>59829, :T_OBJECT=>6,
:T_CLASS=>542, :T_MODULE=>100021, :T_FLOAT=>7, :T_STRING=>3332,
:T_REGEXP=>22, :T_ARRAY=>23868, :T_HASH=>10, :T_BIGNUM=>3, :T_FILE=>3,
:T_DATA=>100324, :T_COMPLEX=>1, :T_NODE=>23807, :T_ICLASS=>19}
100000 MODULES GARBAGE COLLECTED WAITING TO END PROGRAM
FINAL OBJECT SPACE OBJECTS : {:TOTAL=>311794, :FREE=>107155, :T_OBJECT=>6,
:T_CLASS=>542, :T_MODULE=>100021, :T_FLOAT=>7, :T_STRING=>3335,
:T_REGEXP=>22, :T_ARRAY=>203, :T_HASH=>10, :T_BIGNUM=>3, :T_FILE=>3,
:T_DATA=>100324, :T_COMPLEX=>1, :T_NODE=>143, :T_ICLASS=>19}
Related questions :
Working with anonymous modules in ruby
Ruby GC using define method

No comments:

Post a Comment