In Ruby, should I use ||= or if defined? for memoization?

后端 未结 3 635
臣服心动
臣服心动 2020-12-30 04:32

Should I use if defined?

 return @current_user_session if defined?(@current_user_session)
 @current_user_session = UserSession.find
3条回答
  •  情歌与酒
    2020-12-30 04:45

    Rails does have memoization, check out the screencast below for a great introduction:

    http://railscasts.com/episodes/137-memoization

    class Product < ActiveRecord::Base
      extend ActiveSupport::Memoizable
    
      belongs_to :category
    
      def filesize(num = 1)
        # some expensive operation
        sleep 2
        12345789 * num
      end
    
      memoize :filesize
    end
    

提交回复
热议问题