gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 07:14:13 25 4
gpt4 key购买 nike

鲁比的 standard uri library在无法修改或修改不会造成伤害的对象上卡住有很多用途:

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

String#split 不会修改它的参数,即使修改了,代码也会正常工作(Ruby 会在下一次调用时使用新的 ':' 实例)。

这里有一些卡住在不能改变的对象上的更多用法(这些都来自generic.rb)

 if @scheme && @scheme != "ftp".freeze 
v.delete!("\t\r\n".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/

关于ruby - #freeze 除了防止修改之外还有其他用途吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31755779/

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