How do I track down a memory leak in my Ruby code?

前端 未结 4 576
一个人的身影
一个人的身影 2020-12-13 00:39

Question

I\'m debugging a memory leak in a rake task. I want to see a call stack of:

  • Living objects
  • What object or line originally allocated
4条回答
  •  鱼传尺愫
    2020-12-13 01:18

    There is a ruby-mass gem, which provides a nice api over ObjectSpace.

    One of the ways to approach the problem is to check references after you've done with your object.

    object = ...
    # more logic
    puts Mass.references(object)
    

    If there is at least one reference, the object is not garbage collected and you need to figure out how to drop that reference. For example:

    object.instance_variable_set("@example", nil)
    
    # or
    
    ObjectSpace.each_object(Your::Object::Class::Name).each do |obj|
      obj.instance_variable_set("@example", nil)
    end
    

提交回复
热议问题