Ruby对象,减少内存使用量

时间:2011-03-04 08:34:48

标签: ruby oop memory-management

class Employee
  attr_accessor :id, :salary, :birthday... # about 10 more attribures

  def qualify_for_raise?  ..... end 

  def qualify_for_promotion? ..... end 

  # 10 more instance method
end

class Review
  def review(employee_array)
    employee_array.map do |employee|
      if employee.qualify_for_raise?
        # ...
      end
      if employee.qualify_for_promotion?
        # ...
      end
      # ... 
    end
  end
end

由于我将创建50,000个Employee对象,所以将所有实例方法从Employee类中取出会更好,因为每个Employee对象都有自己的实例方法副本吗?如果这是真的,我设计了我的类,如下所示,我更喜欢声明方法来操作Employee类本身内的Employee数据。有没有办法找出有/没有实例方法的Employee对象的大小?

class Employee
  att_accessor :id, :salary, :birthday... # about 10 more attribures
end

class Review
  def review(employee_array)
    employee_array.map do |employee|
      if is_qualify_for_raise(employee)
        # ...
       end
       if is_qualify_for_promotion(employee)
         # ...
       end
       # ... 
     end
   end

   def is_qualify_for_raise(employee)  ..... end 
   def is_qualify_for_promotion(employee) ..... end 
   # 10 more methods
end

1 个答案:

答案 0 :(得分:3)

对象的实例不包含其实例方法的副本,因此对象具有的实例方法的数量不会影响性能。