Calling GC.start
or ObjectSpace.garbage_collect
does not mean that a garbage collection will be performed. It's only a hint to the Ruby runtime.
On some platforms it isn't even possible for the Ruby runtime to initiate a garbage collection, because the garbage collector isn't even part of the Ruby runtime, e.g on JRuby or IronRuby.
In general, the Ruby runtime will decide on its own when it will perform a garbage collection. Usually, that's when it runs out of memory. 100000 modules aren't that big, so there's simply no need to perform a GC cycle.
Also, most Ruby implementations will never release memory back to the OS, even after a GC cycle.
So, just the fact that the ObjectSpace
doesn't shrink doesn't necessarily mean that you have memory leak. It could simply mean that the Ruby runtime didn't yet deem it necessary to run a GC cycle.
Also note that if you run this code from IRb, Pry, an IDE console or some other non-standard environment, then it may be the case that those hold on to some of those modules. For example, Pry stores the results of the last 100 commands in a history array. (Try evaluating _out_[5]
in Pry, after entering your example program.)