【问题标题】:What's the optimal way to find if a given hour belongs to peak season查找给定时间是否属于旺季的最佳方法是什么
【发布时间】:2016-07-26 05:19:14
【问题描述】:

我正在开发一个按小时计费的酒店预订应用程序。有一个peak_seasons 表存储start_dateend_date。 Peak_Seasons 是我的应用程序中当前年份的预定义日期。每当客户在选定的时间进行预订时,我必须检查这些时间是否属于旺季,以便我可以为这些时间应用不同的费率。

这个操作太频繁了,我想优化一下。需要想法。我目前的伪代码是这样的:

def calculate_price(customer_start_time, customer_end_time)
    price = 0
    (customer_start_time.to_i...customer_end_time.to_i).step(1.hour) do |hour|
    //now check if this hour belongs to peak season over here
    if peak_seasons?(hour)
      price += price + peak_season_price
    else
      price += price + standard_price
    end
    return price
end

//peak_seasons? somewhere
def peak_seasons?(hour)
    PeakSeason.where("start_date <= ? and end_date >= ?", hour.to_date, hour.to_date).any?
end

当数百名客户检查选定时间的价格时,我猜这不是有效的代码,然后它将在选定的每个小时从数据库中获取数据。如何优化?

【问题讨论】:

  • customer_start_time, customer_end_time DateTime?
  • 您可以使用BETWEEN 进行查询,? BETWEEN start_date AND end_date。您可以查询四个可能的区间交叉点,而不是每小时查询一次,最多 4 个查询。
  • @neydroid 是的,customer_start_time, customer_end_time 是日期时间。 @sschmeck,谢谢,是的,我可以通过检查间隔而不是小时来减少查询。有什么方法可以让我们只需要一次获取旺季并将其存储在内存中吗?会更好吗?
  • 其实客户只能选择从今天起3个月内的start_time和end_time。但是旺季是提前为全年预先定义的。那么我为什么不利用它,在 Rails 的一些内存中获取和存储旺季,并且只在需要时更新该内存。这样的事情可能吗?

标签: ruby-on-rails ruby database ruby-on-rails-4 rails-activerecord


【解决方案1】:

您可以通过缓存所有PeakSeason 数据并使用Interval tree(另见this answer)进行计算来创建一个超级高效的解决方案。但你说“我猜这效率不高”——老实说,我建议不要进行这种优化,除非你真的知道 存在性能问题。

【讨论】:

    【解决方案2】:

    您可以尝试一次选择给定时间间隔内的所有 PeakSeason 记录。

    def all_peak_seasons(customer_start_time, customer_end_time)
      PeakSeason.where(":start_time BETWEEN start_date AND end_date OR "\
                       ":end_time BETWEEN start_date AND end_date OR "\
                       "start_date BETWEEN :start_time AND :end_time",
                       {start_time: customer_start_time, end_time: customer_end_time}) 
    end
    

    【讨论】:

      猜你喜欢
      • 2010-12-02
      • 2010-12-14
      • 2019-09-16
      • 2016-03-11
      • 1970-01-01
      • 2012-04-02
      • 2012-03-13
      • 2013-10-13
      • 2016-01-08
      相关资源
      最近更新 更多