加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby – #freeze除防止修改外还有其他用途吗?

发布时间:2020-12-17 03:29:25 所属栏目:百科 来源:网络整理
导读:Ruby的 standard uri library有很多用于冻结对象的用法,这些对象要么无法修改,要么修改不会造成伤害: user,password = ui.split(':'.freeze,2) # from generic.rb String#split不会修改它的参数,即使它确实如此,代码也能正常工作(Ruby将在下次调用时使用新
Ruby的 standard uri library有很多用于冻结对象的用法,这些对象要么无法修改,要么修改不会造成伤害:

user,password = ui.split(':'.freeze,2)     # from generic.rb

String#split不会修改它的参数,即使它确实如此,代码也能正常工作(Ruby将在下次调用时使用新的’:’实例).

以下是对无法更改的对象进行冻结的更多用法(这些都来自generic.rb)

if @scheme && @scheme != "ftp".freeze 
 v.delete!("trn".freeze)
 str << ':'.freeze

为什么有这么多看似不必要的#freeze调用? #freeze除了防止修改其接收器之外还有用吗?

解决方法

这个问题的答案可以在这里找到: http://tmm1.net/ruby21-fstrings/

In Ruby 2.1,“str”.freeze is optimized by the compiler to return a single shared frozen strings on every invocation. An alternative “str”f syntax was implemented initially,but later reverted.

Although the external scope of this feature is limited,internally it is used extensively to de-duplicate strings in the VM. Previously,every def method_missing(),the symbol :method_missing and any literal “method_missing” strings in the code-base would all create their own String objects. With Ruby 2.1,only one string is created and shared. Since many strings are commonly re-used in any given code base,this easily adds up. In fact,large applications can expect up to 30% fewer long-lived strings on their heaps in 2.1.

For 2.2,there are plans to expose this feature via a new String#f. There’s also a proposal for a magic immutable: string comment to make frozen strings default for a given file.

TL; DR:Ruby解析器使用.freeze处理字符串文字,而不是没有.freeze的字符串文字.带有.freeze的字符串不会在每次使用时重新实例化,而是来自像符号这样的全局冻结字符串池.

这是一篇关于这个主题的更深入的文章:http://josephyi.com/freeze/

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读