ActiveRecord: count vs. size vs. length
Apr 21 2009 // Comments
Do you know the differences between the following ActiveRecord association #count, #size, and #length methods? Apparently, I did not... I ran into this when trying to optimize some controllers/views. I noticed that extra SQL COUNT's were occurring, and I was not explicitly calling them. This led me down a path to the #empty? method for a has_many association.
For example:
Controller#show:
@contact = Contact.find(params[:id], :include => :addresses)
View#show:
if @contact.addresses.empty?
Sorry, no address on file.
end
In the view, I was checking to see if "addresses" was empty before looping through and displaying information about them or displaying an "empty" message to the user. This call to #empty? indirectly calls "size" for the association and therefore issues a SQL COUNT statement to determine how many associated models existed.
Now, while this is perfectly acceptable behavior -- my intention was to check the size of the collection "in-memory" before looping through and displaying them (this would be the more efficient way since I'm taking advantage of the :include option of the #find method). I started investigating when I ran across Josh's blog entry about these very methods.
After reading his blog, I realized I was really after the in-memory length of the associated collection; so my view now looks like this:
if @contact.addresses.length.zero?
Sorry, no address on file.
end
This change eliminated the extra SQL COUNT statement, and therefore optimized the page load slightly. Now I realize this is a minor optimization, but scaled up on a very large table that would take a bit of time to run COUNT statement against; this could actually shave off some significant page load time by just paying attention to which collection "size" method you're calling.
~ cheers ~

I'm a Ruby and Rails programmer with tons of web development
experience with various technologies. I'm an active private pilot and
always looking for excuse to go flying.