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.
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
:
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With