Wrong way, Right way - Part 1 - Optimized conditional data sections
Part of a series about common Ruby mistakes that make things slower or are just plain wrong. Not the style of the code (indentation, methods names etc), but the actual code itself. All examples use Ruby 1.9.2 and Rails 3.0.x.
Part 1 - Optimized conditional data sections
The Wrong Way
@comments = Comment.order(:position)
if @comments.count > 0
@comments.each do |comment|
…
end
end
Whats wrong? The conditional fires one query for count, and then the loop fires another one to get them again and instantiate them.
The Right Way
@comments = Comment.order(:position)
if @comments.to_a.any?
@comments.each do |comment|
…
end
end
Whats better? Only one query is made. The conditional loads the records, so if there are any to loop over, they are already loaded and ready to go without an extra query.
Questions? Comments? Let me know what you thought.