nil.to_s Produces a Frozen String?
Asked Answered
M

1

9

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')
Malodorous answered 20/8, 2020 at 0:0 Comment(2)
What version of Ruby? And which line triggers the error?Fairy
I am confused. Why would the presence or absence of # frozen_string_literal: true matter?Pectinate
V
13

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.

Vaivode answered 20/8, 2020 at 0:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.