【问题标题】:Ruby on Rails optimalization of some codeRuby on Rails 一些代码的优化
【发布时间】:2013-07-23 00:03:02
【问题描述】:

我有一些使用 minmax 算法来定位鸟类的简单代码。一切正常,但我发现我的编程不好,我相信有更好的解决方案。我在 RoR 方面没有那么有经验,但如果有人知道更好的方法来实现相同的解决方案,那么我很高兴 ;)。

我讨厌两个部分,我必须创建 4 个列表来确定不同组合的最大值或最小值(最小值-最大值算法的核心)和非常丑陋的 SQL hack。

谢谢!

 def index
# fetch all our birds
@birds = Bird.all
# Loop over the birds
@birds.each do |bird|
  @fixed = Node.where("d7type = 'f'")
  xminmax = []
  xmaxmin = []
  yminmax = []
  ymaxmin = []
  @fixed.each do |fixed|
    rss = Log.find_by_sql("SELECT logs.fixed_mac, AVG(logs.blinker_rss) AS avg_rss FROM logs
              WHERE logs.blinker_mac = '#{bird.d7_mac}' AND logs.fixed_mac = '#{fixed.d7_mac}' ORDER BY logs.id DESC LIMIT 30")
    converted_rss = calculate_distance_rss(rss[0].attributes["avg_rss"])
    xminmax.push(fixed.xpos + converted_rss)
    xmaxmin.push(fixed.xpos - converted_rss)
    yminmax.push(fixed.ypos + converted_rss)
    ymaxmin.push(fixed.ypos - converted_rss)
  end

  pos = {x: (xminmax.min + xmaxmin.max) / 2, y: (yminmax.min + ymaxmin.max) / 2}
  puts pos


end

结束

【问题讨论】:

  • 您可以尝试通过加入 Birds,node,logs 表在单个 sql 查询中获取 xminmax , xmaxmin, yminmax, ymaxmin 。如果不可能,您可以将逻辑放在存储过程中。并且只调用一次存储过程。我在我的一个应用程序中尝试了这个原理,结果非常棒。
  • 我尝试了一个 SQL,但它使事情变得非常复杂。你将如何处理存储过程?你能写一个简单的例子作为答案吗(不赞成)。谢谢!

标签: mysql ruby-on-rails optimization


【解决方案1】:

您可以做的两件事是(假设 Birds 可能是一张大桌子)将 Bird.all 更改为

Bird.find_each do |bird|
  ... code ...
end

这是一种循环遍历许多表记录的更有效方式。

第二个:从每个循环中取出@fixed = Node.where("d7type = 'f'"),因为它的查询不需要任何变量。将它放在循环之上,这样它就不会每次都执行。

3rd(与其说是优化,但只是更安全的代码):您的Log.find_by_sql 看起来很简单,可以使用 active_record,您可以将其更改为:

Log.select('fixed_mac, AVG(logs.blinker_rss) AS avg_rss, blinker_mac').
    where(blinker_mac: bird.d7_mac, fixed_mac: fixed.d7_mac).
    order('id DESC').limit(30)

converted_rss = calculate_distance_rss(rss.first.avg_rss)

其他一切看起来都很好。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-08
    相关资源
    最近更新 更多