active_attr icon indicating copy to clipboard operation
active_attr copied to clipboard

Memory leak with ActiveAttr::BasicModel and Class.new

Open rmadamanchi opened this issue 5 years ago • 0 comments

We recently ran into a memory issue that I successfully traced back to the creation of an anonymous class (Class.new) based on a type that includes AttriveAttr::BasicModel.

Below is the simplest form of the scenario demonstrating the Class objects eating up memory. It looks like the Class objects are somehow being held on to - which might be ok in general, but not ideal in case of an anonymous class instance created each time.

Running this test for any class that does not involve AttriveAttr::BasicModel clears up the memory as expected.

I am not proposing that creating anonymous classes like this is a best practice. We removed this pattern from our code base - but ideally, this shouldn't have happened.

require 'active_attr'

class MyClass
  include ActiveAttr::BasicModel
end

def class_object_count
  ObjectSpace.count_objects[:T_CLASS].to_s
end

puts "#{class_object_count} <- # Classes Before"

100000.times {Class.new(MyClass)}
puts "#{class_object_count} <- # Classes After"

GC.start
puts "#{class_object_count} <- # Classes After GC"

rmadamanchi avatar Sep 17 '18 13:09 rmadamanchi