stevec
stevec

Reputation: 52308

Garbage collect in ruby?

I can see related questions asked before

In some languages, there's a specific way to force garbage collection. For example in R, we can call gc() and it will free up memory that was previously used to store objects that have since been removed.

Is there any way to do this in ruby?

In case it's relevant, I'm running a very long loop and I think it's slowly accumulating a little memory use each iteration, and I would like to force garbage collection every 100th iteration or so just to be sure e.g. (pseudo code) if index % 100 == 0 then gc(). Also note I intend to use this in a rails app, although I don't think that's relevant (since garbage collection would be entirely a ruby feature, nothing to do with rails)

Upvotes: 2

Views: 1975

Answers (2)

Jörg W Mittag
Jörg W Mittag

Reputation: 369468

No, there is no way to do it in Ruby.

There is a method called GC::start, and the documentation even says:

Initiates garbage collection, even if manually disabled.

But that is not true. GC::start is simply an advisory from your code to the runtime that it would be safe for your application to run a garbage collection now. But that is only a suggestion. The runtime is free to ignore this suggestion.

The majority of programming languages with automatic memory management do not give the programmer control over the garbage collector.

If Ruby had a method to force a garbage collection, then it would be impossible to implement Ruby on the JVM and neither JRuby nor TruffleRuby could exist, it would be impossible to implement Ruby on .NET and IronRuby couldn't exist, it would be impossible to implement Ruby on ECMAScript and Opal couldn't exist, it would be impossible to implement Ruby using existing high-performance garbage collectors and RubyOMR couldn't exist.

Since it is in generally desirable to give implementors freedom to implement optimizations and make the language faster, languages are very cautious on specifying features that so drastically restrict what an implementor can do.

I am quite surprised that R has such a feature, especially since that means it is impossible to implement high-performance implementations like FastR in a way that is compliant with the language specification. FastR is up to more than 35× faster than GNU R, so it is obvious why it is desirable for something like FastR to exist. But one of the ways FastR is faster, is that it uses a third-party high-performance garbage collected runtime (either the GraalVM or the JVM) that does not allow control over garbage collection, and thus FastR can never be a compliant R implementation.

Interestingly, the documentation of gc() has this to say:

[T]he primary purpose of calling gc is for the report on memory usage.

Upvotes: 4

D. SM
D. SM

Reputation: 14490

This is done via GC.start.

--

Upvotes: 0

Related Questions