Does creating intermediate variables cause the garbage collector to do more work?

That is, is there any difference between:

output = :asdf.to_s.upcase

and

str = :asdf.to_s
output = str.upcase

? (Assume str is never referenced again.)

有帮助吗?

解决方案

It would be a trivial amount of extra work when marking objects still referenced, assuming both str and output were still in scope (i.e. the binding where they exist was still active) when the GC mark phase began. Both variables would start a mark on the same string. I don't know, but suspect that when marking objects as still viable, if Ruby comes across an item already marked, it will probably stop recursing and go to its next item at the same level. In this case the String is a single object without child objects to mark further, so it's one quick call to rb_gc_mark repeated for each reference to the String - one case where it is marked, and another case where Ruby notes it has already been marked and stops recursing.

If neither variable were in any active binding when GC mark phase began, it is no extra work, the String referenced would not get marked (no work) and the sweep phase would delete it just once (same work no matter how many references were active before).

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top