为什么unused_variable_2 和unused_variable_3 会被垃圾回收,但unused_variable_1 不会?
# leaky_boat.rb
require "memprof"
class Boat
def initialize(string)
unused_variable1 = string[0...100]
puts unused_variable1.object_id
@string = string
puts @string.object_id
end
end
class Rocket
def initialize(string)
unused_variable_2 = string.dup
puts unused_variable_2.object_id
unused_variable_3 = String.new(string)
puts unused_variable_3.object_id
@string = string
puts @string.object_id
end
end
Memprof.start
text = "a" * 100
object_id_message = "Object ids of unused_variable_1, @string, unused_variable_2, unused_variable_3, and another @string"
before_gc_message = "Before GC"
after_gc_message = "After GC"
puts object_id_message
boat = Boat.new(text)
rocket = Rocket.new(text)
puts before_gc_message
Memprof.stats
ObjectSpace.garbage_collect
puts after_gc_message
Memprof.stats
Memprof.stop
运行程序:
$ uname -a
Linux [redacted] 3.2.0-25-generic #40-Ubuntu SMP Wed May 23 20:30:51 UTC 2012 x86_64 x86_64 x86_64 GNU/Linux
$ ruby --version # Have to use Ruby 1.8 - memprof doesn't work on 1.9
ruby 1.8.7 (2011-06-30 patchlevel 352) [x86_64-linux]
$ ruby -rubygems leaky_boat.rb
Object ids of unused_variable_1, @string, unused_variable_2, unused_variable_3, and another @string
70178323299180
70178323299320
70178323299100
70178323299060
70178323299320
Before GC
2 leaky_boat.rb:6:String
2 leaky_boat.rb:26:String
1 leaky_boat.rb:9:String
1 leaky_boat.rb:7:String
1 leaky_boat.rb:32:Rocket
1 leaky_boat.rb:31:Boat
1 leaky_boat.rb:29:String
1 leaky_boat.rb:28:String
1 leaky_boat.rb:27:String
1 leaky_boat.rb:20:String
1 leaky_boat.rb:18:String
1 leaky_boat.rb:17:String
1 leaky_boat.rb:16:String
1 leaky_boat.rb:15:String
After GC
1 leaky_boat.rb:6:String
1 leaky_boat.rb:32:Rocket
1 leaky_boat.rb:31:Boat
1 leaky_boat.rb:29:String
1 leaky_boat.rb:28:String
1 leaky_boat.rb:27:String
1 leaky_boat.rb:26:String