Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 365
Touqeer Avatar asked Jul 27 '17 09:07

Touqeer


2 Answers

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.

like image 129
Igor Drozdov Avatar answered Oct 21 '22 04:10

Igor Drozdov


pluck: retrieve just names from users, put them in an array as strings (in this case) and give it to you.

select: retrieve all the users from db with just the 'name' column and returns a relation.

collect/map (alias): retrieve all the users from db with all columns, put them in an array of User objects with all the fields, then transform every object in just the name and give this names array to you.

I put this in order of performance to me.

like image 6
Ursus Avatar answered Oct 21 '22 05:10

Ursus