0

プログラム - I

p RUBY_VERSION

a = "A"
b = "B"

p "#{a}"
p "#{b}"

p "Garbage Count => #{GC.count}"

b = "D"

p "Garbage Count => #{GC.count}"

GC.start

p "Garbage Count => #{GC.count}"

p "#{a}"
p "#{b}"

出力:

"1.9.3"
"A"
"B"
"Garbage Count => 1"
"Garbage Count => 1"
"Garbage Count => 2"
"A"
"D"

Program I出力で、p "Garbage Count => #{GC.count}"どちらが混乱したか.混乱1,1,2garbage objectsカウントにありました。Program-Iそこで、以下の修正版を試してみました。

コメントアウトしたところGC.start。その出力を見ると、最初のプログラムで宣言しProgram -IIたように見えます。GC.startこれにより、参照なしオブジェクトが破壊されました "B"

プログラム - II

p RUBY_VERSION

a = "A"
b = "B"

p "#{a}"
p "#{b}"

p "Garbage Count => #{GC.count}"

b = "D"

p "Garbage Count => #{GC.count}"

#GC.start

p "Garbage Count => #{GC.count}"

p "#{a}"
p "#{b}"

出力:

"1.9.3"
"A"
"B"
"Garbage Count => 1"
"Garbage Count => 1"
"Garbage Count => 1"
"A"
"D"

最終的な質問は次のとおりです。

(a)GC.start出力から明らかなように、1 つのオブジェクトが破棄される前。それは何の物体でしたか?

(b) 非参照オブジェクトBがなくても破棄されなかったのはなぜGC.startですか?

編集

p GC.count
p GC.disable
p GC.count

出力

1
false
1

abive コードで無効にgarbage collectionしました。最後GC.countの出力が として表示されるのは1なぜですか?

上記のように頭に浮かんだ質問を理解するのを手伝ってくれる人はいますか。

4

1 に答える 1

1

GC.count doesn't return the number of garbage collected objects - it returns the number of times the garbage collector has run, so calling GC.start will always increment it by one.

A bunch of code gets executed before your code starts to run, so it's not that surprising that some garbage collection may occur.

Disabling gc isn't going to undo the garbage collections that have already happened.

于 2013-03-18T13:23:11.443 に答える