Is there a convention for memoization in a method call?

前端 未结 6 1515
清酒与你
清酒与你 2021-02-19 04:14

I want to avoid reevaluation of a value in method call. Untill now, I was doing this:

def some_method
  @some_method ||= begin
    # lot\'s of code
  end
end
         


        
6条回答
  •  孤城傲影
    2021-02-19 04:53

    I normally do it like in Agis answer or:

    def filesize() @filesize ||=
      calculate_filesize
    end
    

    BTW:

    I often use this memoization technique:

    def filesize() @_memo[:filesize] ||=
      calculate_filesize
    end
    

    Which will allow you to later clear all memoized variables with one simple @_memo.clear. The @_memo variable should be initialized like this Hash.new { |h, k| h[k] = Hash.new }. It gives you many of the adventages of using ActiveSupport::Memoize and similar meta programmed techniques which might be much slower.

提交回复
热议问题