2

Curious which of these is better performance wise. If you have a User with many PlanDates, and you know your user is the user with an id of 60 in a variable current_user, is it better to do:

plan_dates = current_user.plan_dates.select { |pd| pd.attribute == test }

OR

plan_dates = PlanDate.joins(:user).where("plan_dates.attribute" => test).where("users.id" => 60)

Asking because I keep reading about the dangers of using select since it builds the entire object...

james
  • 3,989
  • 8
  • 47
  • 102

2 Answers2

4

select is discouraged because, unlike the ActiveRelation methods where, joins, etc., it's a Ruby method from Enumerable which means that the entire user.plan_dates relation must be loaded into memory before the selection can begin. That may not make a difference at a small scale, but if an average user has 3,000 plan dates, then you're in trouble!

So, your second option, which uses just one SQL query to get the result, is the better choice. However, you can also write it like so:

user.plan_dates.where(attribute: test)

This is still just one SQL query, but leverages the power of ActiveRelation for a more expressive result.

Robert Nubel
  • 7,104
  • 1
  • 18
  • 30
1

The second. The select has to compare objects on the code level, and the second is just a query.

In addition, the second expression may not be actually executed unless you use the variable, while the first will be always executed.