Nan*_*ego 8 postgresql activerecord ruby-on-rails ruby-on-rails-4
我期待这个电话
Model.maximum(:updated_at)
要快于这个
Model.order(:updated_at).last.updated_at
有人能证实这个断言吗?如果是真的,解释原因?
您可以使用Benchmark 模块轻松进行调查,例如:
require 'benchmark'
n = 50000
Benchmark.bm do |x|
  x.report('maximum') { n.times.do; v1; end }
  x.report('order-pluck') { n.times do; v2; end }
end
def v1
  clear_cache
  Model.maximum(:updated_at)
end
def v2
  clear_cache
  Model.order(:updated_at).pluck(:updated_at).last
end
def clear_cache
  ActiveRecord::Base.connection.query_cache.clear
end
为了使 n > 1 值得这样做,您必须清除可能涉及的各种缓存。您的数据库服务器中可能有一个缓存,与 ActiveRecord 缓存分开。例如要清除 Mysql 缓存,您可以调用:
`mysql mydb -e 'RESET QUERY CACHE'`
| 归档时间: | 
 | 
| 查看次数: | 3705 次 | 
| 最近记录: |