User314159
User314159

Reputation: 8065

Which of these two AR queries is more efficient? (ie. is it better to outsource some query work to Ruby )

  @users = Hash.new
  @users[:count] = User.count(:all, :joins => my_join, :conditions => my_conditions)
  @users[:data] = User.find(:all, :joins => my_join, :conditions => my_conditions)

or

  @users = Hash.new
  @users[:data] = User.find(:all, :joins => my_join, :conditions => my_conditions)
  @users[:count] = @users[:data].count

It seems like the first option consists of two database queries (which from what I read is expensive) while in the second one, we only make one database query and do the counting work at the Ruby level.

Which one is more efficient?

Upvotes: 0

Views: 176

Answers (1)

Domon
Domon

Reputation: 6823

The second one is better, since, just like you said, it saves a database query.

p.s.

Please be careful if you use some new finder methods introduced in Rails 3, then calling count after would fire a COUNT(*) query:

users = User.where(...)    # SELECT "users".* FROM "users" WHERE ...
users_count = users.count  # SELECT COUNT(*) FROM "users" WHERE ...

To prevent that, you might want to call size:

users = User.where(...)   # SELECT "users".* FROM "users" WHERE ...
users_count = users.size  # No database query

Upvotes: 3

Related Questions