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.
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.
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.
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.
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
anddef 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With