gpt4 book ai didi

ruby - 为什么 `ObjectSpace.each_object(String)` 几乎包含任何字符串?

转载 作者:数据小太阳 更新时间:2023-10-29 08:32:00 26 4
gpt4 key购买 nike

在 Mike H-R 和 Stefan 对 a question of mine 发表评论后,我注意到 ObjectSpace.each_object(String) 几乎包含我能想到的任何字符串:

strings = ObjectSpace.each_object(String)
strings.include?("some random string") # => true

strings = ObjectSpace.each_object(String).to_a
strings.include?("some random string") # => true

我认为 strings 应该只包含当时存在的字符串。为什么它几乎包含任何字符串?

然而,当我计算 strings 的长度时,它返回一个有限的数字:

ObjectSpace.each_object(String).to_a.length # => 15780

这是在 Ruby 2.1.2p95(2014-05-08 修订版 45877)[x86_64-linux] 解释器和 irb 上观察到的。

这与 Ruby 2.1 中引入的卡住字符串文字优化有什么关系吗?

最佳答案

IRB 中编写代码时,字符串会在键入时添加到 ObjectSpace 中:

strings = ObjectSpace.each_object(String)
strings.include?("some random string") # => true

strings = ObjectSpace.each_object(String).to_a
strings.include?("some other random string") # => false

当尝试在 rb 文件中执行此操作时,文本已经存在,因为它是在解析文件时添加的

测试.rb

strings = ObjectSpace.each_object(String)
strings.include?("some random string") # => true

strings = ObjectSpace.each_object(String).to_a
strings.include?("some other random string") # => true

strings = ObjectSpace.each_object(String).to_a
strings.include?("some other random string " + "dynamically built") # => false

关于ruby - 为什么 `ObjectSpace.each_object(String)` 几乎包含任何字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24064652/

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