符号垃圾收集 Ruby 2.2.1
Garbage Collection of Symbols Ruby 2.2.1
所以从 Ruby 2.2+ 版本引入了符号垃圾收集。我在 irb 中写了以下代码片段:
before = Symbol.all_symbols.size #=>3331
100_000.times do |i|
"sym#{i}".to_sym
end
Symbol.all_symbols.size #=> 18835
GC.start
Symbol.all_symbols.size #=>3331
因此,正如预期的那样,它收集了使用 to_sym
动态生成的所有符号。
那么 GC 是如何知道收集哪些符号的呢?即使它们在程序中被引用,它会收集符号吗?符号垃圾回收是如何工作的?如果我创建的其中一个符号在程序中被引用,它还会收集它吗?
我正在使用 Ruby 2.2.1。
Basically, all symbols created dynamically while Ruby is running (via to_sym
, etc.) can be garbage collected because they are not being used behind the scenes inside the Ruby interpreter. However, symbols created as a result of creating a new method or symbols that are statically inside of code will not be garbage collected. For example :foo
and def foo; end
both will not be garbage collected, however "foo".to_sym
would be eligible for garbage collection.
所以从 Ruby 2.2+ 版本引入了符号垃圾收集。我在 irb 中写了以下代码片段:
before = Symbol.all_symbols.size #=>3331
100_000.times do |i|
"sym#{i}".to_sym
end
Symbol.all_symbols.size #=> 18835
GC.start
Symbol.all_symbols.size #=>3331
因此,正如预期的那样,它收集了使用 to_sym
动态生成的所有符号。
那么 GC 是如何知道收集哪些符号的呢?即使它们在程序中被引用,它会收集符号吗?符号垃圾回收是如何工作的?如果我创建的其中一个符号在程序中被引用,它还会收集它吗?
我正在使用 Ruby 2.2.1。
Basically, all symbols created dynamically while Ruby is running (via
to_sym
, etc.) can be garbage collected because they are not being used behind the scenes inside the Ruby interpreter. However, symbols created as a result of creating a new method or symbols that are statically inside of code will not be garbage collected. For example:foo
anddef foo; end
both will not be garbage collected, however"foo".to_sym
would be eligible for garbage collection.