↓ Ir para o conteúdo principal

← todas as notas

📎 Webclip

Getting to Know Pluck and Select

The post explains that select returns ActiveRecord model objects, while pluck returns plain values and skips the overhead of building models. It argues that this difference matters for performance even when query time looks similar.

Reading notes
#

  • select was the standard way to query a single field before pluck existed.
  • User.select(:id).to_a returns an array of User models with only id loaded.
  • pluck was introduced in Rails 3.2 to skip ActiveRecord object construction.
  • User.pluck(:id) returns an array of integers instead of model instances.
  • The database query time can be similar, but object creation makes select slower.
  • A benchmark over 10,000 users showed select was 91% slower than pluck.
  • pluck was created to remove the overhead seen in patterns like User.select(:id).map(&:id).
  • As of Rails 4.0, pluck can take multiple columns.
  • select accepts multiple columns as separate arguments or as an array, but pluck does not accept an array.
  • select is useful when the returned records need model methods.
  • The post summarizes the distinction as pluck for model values and select for model objects.