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

saw*_*awa 2 ruby objectspace

在Mike HR和Stefan对我的一个问题发表评论之后,我注意到ObjectSpace.each_object(String)包括我能想到的任何字符串:

strings = ObjectSpace.each_object(String)
strings.include?("some random string") # => true
Run Code Online (Sandbox Code Playgroud)

要么

strings = ObjectSpace.each_object(String).to_a
strings.include?("some random string") # => true
Run Code Online (Sandbox Code Playgroud)

我认为strings应该只包括那时存在的字符串.为什么它包含任何字符串?

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

ObjectSpace.each_object(String).to_a.length # => 15780
Run Code Online (Sandbox Code Playgroud)

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

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

Uri*_*ssi 5

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
Run Code Online (Sandbox Code Playgroud)

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

test.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
Run Code Online (Sandbox Code Playgroud)

  • 我通过行为得出结论,我看到加载的ruby文件中的文字字符串在其代码运行之前被加载到`ObjectSpace`. (2认同)
  • 我很确定IRB在你输入之前不会将字符串添加到`ObjectSpace`;) (2认同)