在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中引入的冻结字符串文字优化有什么关系吗?
在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)
| 归档时间: |
|
| 查看次数: |
162 次 |
| 最近记录: |