Search code examples
ruby-on-railsrubyactiverecordrails-activerecord

Which one is faster between map, collect, select and pluck?


I have been using different methods to get specific fields from active record, But which one is faster and preferred to use and how are they different from one another?

User.all.collect(&:name)
User.all.pluck(:name)
User.all.select(:name)
User.all.map(&:name)

Thanks for your help in advance.


Solution

  • Usage of any of these methods requires different use cases:

    Both select and pluck make SQL's SELECT of specified columns (SELECT "users"."name" FROM "users"). Hence, if you don't have users already fetched and not going to, these methods will be more performant than map/collect.

    The difference between select and pluck:

    • Performance: negligible when using on a reasonable number of records
    • Usage: select returns the list of models with the column specified, pluck returns the list of values of the column specified. Thus, again, the choice depends on the use case.

    collect/map methods are actually aliases, so there's no difference between them. But to iterate over models they fetch the whole model (not the specific column), they make SELECT "users".* FROM "users" request, convert the relation to an array and map over it.

    This might be useful, when the relation has already been fetched. If so, it won't make additional requests, what may end up more performant than using pluck or select. But, again, must be measured for a specific use case.