开发者

What is the difference between these two statements, and why would you choose them?

I'm a beginner at rails. And I've come to understand two different ways to return the same result.

What is the difference between these two? And what situation would require you to choose one from the other?

Example 1:

Object.find(:all).select {|c| c.name == "Foobar" }.size

Example 2:

Object.count(:co开发者_Python百科nditions => ['name = ?', 'Foobar'])

FURTHER NOTE:

I seriously wish I could vote everyone correct answers for this one. Thank you so much. I just had a serious rails affirmation.


Object.count always hits the DB, and the find()....size() call can optimize. Good discussion here

http://rhnh.net/2007/09/26/counting-activerecord-associations-count-size-or-length


Example 1:

This constructs a query:

SELECT * FROM objects

then turns all the records into a collection of objects in your memory, then iterates through every object to see if it meets the condition, and then counts the number of elements that meet condition.

Example 2:

This constructs a query:

SELECT count(id) FROM objects WHERE name = 'Foobar'

lets sql do all the hard work, and returns just an integer - a number of objects meeting condition.

Usually you want no 2 - faster and less memory


Example 1 will load all of your records from the DB (assuming Object is an ActiveRecord model), then uses Ruby to reduce the set, and then return the size of that array. So this is potentially memory and CPU heavy - not good.

Example 2 performs the count in SQL, so all the heavy lifting is performed in the database, not in Ruby. Much better :)


In example 1, you are getting all objects from the datastore, and then iterating over all of them, selecting the objects that has the name Foobar. And then getting the size of that array. Example 1 is the clear loser here.

Example 1 sql:

select * from whatever
# then iterate over entire array

Example two executes a where clause in SQL to the datastore.

select count(id) from whatever where name = 'foobar'
# The SQL above is sql-server accurate, but not necessarily mysql or sqlite3
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜