Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nil.to_s Produces a Frozen String?

Tags:

ruby

ruby-2.7

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')
like image 916
Larry North Avatar asked Aug 20 '20 00:08

Larry North


1 Answers

This was added in Ruby 2.7 -- It's documented explicitly in the release notes.

Module#name, true.to_s, false.to_s, and nil.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 of to_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.

like image 156
John Ledbetter Avatar answered Oct 25 '22 07:10

John Ledbetter