Rails。使用vs大于/小于

时间:2016-03-15 14:01:04

标签: ruby-on-rails-4

我希望在我的rails应用程序中加快我的一个查询。

现在我正在使用 .where(['num_units >= ? and num_units <= ?',min_units,max_units])

将其更改为更快或更有益 .where(num_units: min_units..max_units)

顺便说一下,这是在Rails 4中。

修改 我意识到我很可能需要为我需要的列编制索引,这会大大加快这个查询的速度。我的一位同事告诉我他们几乎完全相同

1 个答案:

答案 0 :(得分:1)

我会通过这种方式检查查询以查看哪一个最快:

Benchmark.measure do
  100000.times do
    # Change 'Class' to your class name.
    Class.where('num_units >= ? and num_units <= ?', min_units, max_units)
  end
end

Benchmark.measure do
  100000.times do
    Class.where('num_units BETWEEN ? AND ?', min_units, max_units)
  end
end

Benchmark.measure do
  100000.times do
    Class.where(num_units: min_units..max_units)
  end
end

按照上述顺序,我在本地测试中回来的时间:

  1. @真实= 3.280792
  2. @真实= 3.312653
  3. @真实= 3.709074
相关问题