【问题标题】:Ruby object, reduce memory usageRuby 对象,减少内存使用
【发布时间】:2011-03-04 20:07:24
【问题描述】:
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

【问题讨论】:

  • 您将attr_accessor 拼错为att_accessor
  • 除了 Andrew 的回答之外,为什么需要同时实例化所有 50000 个?

标签: ruby oop memory-management


【解决方案1】:

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

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2013-05-21
  • 1970-01-01
  • 1970-01-01
  • 2011-09-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多