pluck当只需要一两个字段时,我一直默认使用,但我最近对性能差异进行了基准测试,并且勇气丢失了:
ActiveRecord::Base.logger.level = 1
n = 5000
Benchmark.bm do |x|
x.report('Country.all: ') { n.times { Country.all } }
x.report('Country.unscoped: ') { n.times { Country.unscoped } }
x.report('base priority_order: ') { n.times { Country.unscoped.with_translations(I18n.locale).order(list_at_top: :desc).order(:name) } }
x.report('.includes(:translations): ') { n.times { Country.unscoped.with_translations(I18n.locale).order(list_at_top: :desc).order(:name).includes(:translations) } }
x.report('.pluck(:name): ') { n.times { Country.unscoped.with_translations(I18n.locale).order(list_at_top: :desc).order(:name).includes(:translations).pluck(:name) } }
x.report('.pluck(:name) only: ') { n.times { Country.unscoped.with_translations(I18n.locale).order(list_at_top: :desc).order(:name).pluck(:name) } }
end
# Results
=begin
user system total real
Country.all: 0.990000 0.020000 1.010000 ( 1.023518)
Country.unscoped: …Run Code Online (Sandbox Code Playgroud) performance activerecord ruby-on-rails database-performance ruby-on-rails-4