Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
390 views
in Technique[技术] by (71.8m points)

ruby - size, length and count in Rails

1.9.3p194 :002 > u = User.find_by_email("[email protected]")
1.9.3p194 :005 > u.addresses.size
 => 1 
1.9.3p194 :006 > u.addresses.length
 => 1 
1.9.3p194 :007 > u.addresses.count 

There is no difference between size, length and count in Rails 3.2.3, isn't it?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

length will load all your objects just to count them; something like:

select * from addresses...

and then return the results count. As you can imagine - it's bad performance

count will just issue

select count(*) from addresses...

which is better, because we are not loading all addresses just to count them

size is smarter - it'll check if the association is already loaded and if true then return the length (without issuing a call to the database).

size also checks for counter_cache if you have a field named address_count in your user model, then size will use this field for the count, so there is no need to issue a count on the addresses table.

if all fails, size will issue a select count(*) on the database


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...