October 12, 2020
This blog is part of our Ruby 3.0 series.
All are excited about
what Ruby 3.0 has
to offer to the Ruby developers.
There is already a lot of buzz
that the feature set of Ruby 3.0
will change the perspective of developers
how they look at Ruby.
One of the important aspects of Ruby 3.0 is optimization.
The part of that optimization is
the introduction of name method for Symbol.
In this blog,
we will take a look
at what name method of class Symbol does
and
why it was introduced.
The new name method is introduced on Symbol
to simply convert a symbol into a string.
Symbol#name returns a string.
Let's see how it works.
irb(main):001:0> :simba.name
=> 'simba'
irb(main):002:0> :simba.name.class
=> String
irb(main):003:0> :simba.name === :simba.name
=> true
Wait what?
Don't we have to_s
to convert a symbol into a string.
Most of us have used to_s method on a Symbol.
The to_s method returns a String object
and
we can simply use it.
But why name?
Using to_s is okay in most cases.
But the problem with to_s is
that it creates a new String object
every time we call it on a symbol.
We can verify this in irb.
irb(main):023:0> :simba.to_s.object_id
=> 260
irb(main):024:0> :simba.to_s.object_id
=> 280
Creating a new object for every symbol to a string conversion
allocates new memory which increases overhead.
The light was thrown on this issue by
schneems (Richard Schneeman)
in a talk at RubyConf Thailand
where he showed how Symbol#to_s allocation
causes significant overhead in ActiveRecord.
This inspired Ruby community
to have a new method name on Symbol
which returns a frozen string object.
This reduces the string allocations dramatically
which results in reducing overhead.
irb(main):001:0> :simba.name.frozen?
=> true
irb(main):002:0> :simba.name.object_id
=> 200
irb(main):003:0> :simba.name.object_id
=> 200
The reason
to bring this feature was
that most of the times
we want a simple string representation
for displaying purpose
or
to interpolate into another string.
The result of to_s is rarely mutated directly.
By introducing this method
we save a lot of objects
which helps in optimization.
Now we know the benefits of name,
we should prefer using name over to_s
when we don't want to mutate a string.
For more information on discussion, official documentation, please head on to Feature #16150 discussion, Pull request and Ruby 3.0 official release preview.
If this blog was helpful, check out our full blog archive.