I'm curious. Is it surprising that the snippet below yields a FrozenError
? The magic comment # frozen_string_literal: true
is not present.
n = nil
s = n.to_s
s.force_encoding('UTF-8')
This was added in Ruby 2.7 -- It's documented explicitly in the release notes.
Module#name
,true.to_s
,false.to_s
, andnil.to_s
now always return a frozen String. The returned String is always the same for a given object. [Experimental] [Feature #16150]
The linked issue has additional reasoning behind the change:
Much of the time when a user calls
to_s
, they are just looking for a simple string representation to display or to interpolate into another string. In my brief exploration, the result ofto_s
is rarely mutated directly.It seems that we could save a lot of objects by providing a way to explicitly request a frozen string. ... This would reduce string allocations dramatically when applied to many common to_s calls.
In summary, it reduces object allocations, which reduces garbage collection overhead, which improves performance.
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