Skip to content

Instantly share code, notes, and snippets.

@flyfy1
Created May 15, 2017 03:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save flyfy1/04236c4dc903a63f8c234d0104cadf9a to your computer and use it in GitHub Desktop.
Save flyfy1/04236c4dc903a63f8c234d0104cadf9a to your computer and use it in GitHub Desktop.
Ruby Memory Leak Examples
module Logger
extend self
attr_accessor :output, :log_actions
def log(&event)
self.log_actions ||= []
self.log_actions << event
end
def play
output = []
log_actions.each { |e| e.call(output) }
puts output.join("\n")
end
end
class Thing
def initialize(id)
# Leaded self here
Logger.log { |output| output << "created thing" }
end
end
def do_something
1000.times { |i| Thing.new(i) }
end
do_something
GC.start
Logger.play
puts ObjectSpace.each_object(Thing).count
module Logger
extend self
attr_accessor :output
def log(&event)
self.output ||= []
event.call(output)
end
def play
puts output.join("\n")
end
end
class Thing
def initialize(id)
Logger.log { |output| output << "created thing #{id}" }
end
end
def do_something
1000.times { |i| Thing.new(i) }
end
do_something
GC.start
Logger.play
puts ObjectSpace.each_object(Thing).count
module Logger
extend self
attr_accessor :output, :log_actions
def log(line)
self.log_actions ||= []
self.log_actions << line
end
def play
log_actions.each { |line| puts line }
end
end
class Thing
def initialize(id)
Logger.log "created thing #{id}"
end
end
def do_something
1000.times { |i| Thing.new(i) }
end
do_something
Logger.play
Logger.log_actions = []
GC.start
puts ObjectSpace.each_object(Thing).count
class LargeObject
def initialize
@data = "x" * 1024 * 1024 * 20
end
end
def do_something
obj = LargeObject.new
trap("TERM") { puts 'oops' }
end
do_something
# force major GC to make sure we free all objects that can be freed
GC.start(full_mark: true, immediate_sweep: true)
puts "LargeObject instances left in memory: %d" %
ObjectSpace.each_object(LargeObject).count
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment