mhaseeb
mhaseeb

Reputation: 1779

Garbage Collection of Symbols Ruby 2.2.1

So garbage collection of symbols has been introduced from Ruby 2.2+ version. I wrote the following the code snippet in irb :

before =  Symbol.all_symbols.size #=>3331
100_000.times do |i|
  "sym#{i}".to_sym
end

Symbol.all_symbols.size #=> 18835
GC.start
Symbol.all_symbols.size #=>3331

So as expected it collected all the symbols generated dynamically with to_sym.

So how does the GC know which symbols to collect? Would it collect the symbols even if they were referenced in the program? How does symbol garbage collection work? If one of the symbols I created were being referenced in the program would it still collect it?

I am using Ruby 2.2.1.

Upvotes: 10

Views: 2032

Answers (1)

iltempo
iltempo

Reputation: 16012

Basically, all symbols created dynamically while Ruby is running (via to_sym, etc.) can be garbage collected because they are not being used behind the scenes inside the Ruby interpreter. However, symbols created as a result of creating a new method or symbols that are statically inside of code will not be garbage collected. For example :foo and def foo; end both will not be garbage collected, however "foo".to_sym would be eligible for garbage collection.

See Richard Schneeman's post as a reference.

Upvotes: 12

Related Questions