gpt4 book ai didi

ruby - nil.to_s 产生一个卡住的字符串?

转载 作者:行者123 更新时间:2023-12-03 20:04:09 24 4
gpt4 key购买 nike

我很好奇。下面的代码片段产生 FrozenError 是否令人惊讶? ?神奇评论# frozen_string_literal: true不存在。

n = nil
s = n.to_s
s.force_encoding('UTF-8')

最佳答案

这是在 Ruby 2.7 中添加的——它明确记录在 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]


链接的问题在更改背后有其他原因:

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.


总之,它减少了对象分配,从而减少了垃圾收集开销,从而提高了性能。

关于ruby - nil.to_s 产生一个卡住的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63496532/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com