我期待这个电话
Model.maximum(:updated_at)
比这个快
Model.order(:updated_at).last.updated_at
有人能证实这个说法吗?如果为真,请解释原因?
最佳答案
您可以使用 the Benchmark module轻松调查,例如:
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'`
关于ruby-on-rails - 更快地找到最后更新的时间戳,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31656897/