Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 256
mhaseeb Avatar asked Dec 10 '15 11:12

mhaseeb


People also ask

Are Ruby symbols garbage collected?

Starting with Ruby 2.2 symbols are now garbage collected. Since the symbols we create aren't referenced by any other object or variable, they can be safely collected. This helps in preventing us from accidentally creating a scenario where a program creates and retains so many objects that it crashes.

What are symbols in Ruby?

Ruby symbols are defined as “scalar value objects used as identifiers, mapping immutable strings to fixed internal values.” Essentially what this means is that symbols are immutable strings. In programming, an immutable object is something that cannot be changed.

Are symbols immutable in Ruby?

Because symbols are immutable, Ruby doesn't have to allocate more memory for the same symbol. That is because it knows that once it put the value in memory, it will never be changed, so it can reuse it. You can easily see this by looking at their object IDs.


1 Answers

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.

like image 61
iltempo Avatar answered Oct 11 '22 14:10

iltempo