I am using Ruby on Rails 3 and I would like to know what is the performance difference for these query statements:
# Case 1
accounts = ids.map { |id| Account.find_by_id(id) }
# Case 2
accounts = ids.map { |id| Account.where(:id => id).first }
There is another way to do things better? If ids are 100, how can I limit the search until accounts are 5?
As @RubyFanatic said, there’s no real difference between those two (they’d both generate the same query), but there is a considerably better way of doing it:
This will generate sql like
select * from accounts where accounts.id in (1,2,3)and will be considerably faster than finding them one at a time.And if you want to only use say 5 of the ids from the array of ids, you’d need to decide which 5 to use. For example, if you wanted to use the first 5;
Or, you could use limit, but this makes the query have to do a little more work still if the ids array is large: