Warum werden unused_variable_2 und unused_variable_3 gesammelt, aber nicht 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 = "Objekt-IDs von unused_variable_1, @string, unused_variable_2, unused_variable_3 und ein weiteres @string"
before_gc_message = "Vor GC"
after_gc_message = "Nach 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
Programm ausführen:
$ 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 # Muss Ruby 1.8 verwenden - memprof funktioniert nicht mit 1.9
ruby 1.8.7 (2011-06-30 patchlevel 352) [x86_64-linux]
$ ruby -rubygems leaky_boat.rb
Objekt-IDs von unused_variable_1, @string, unused_variable_2, unused_variable_3 und ein weiteres @string
70178323299180
70178323299320
70178323299100
70178323299060
70178323299320
Vor 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
Nach 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