Simplified Question
Why is SELECT 1 FROM table WHERE {constraints}
followed by Rails' array.length performing faster than SELECT COUNT(1) FROM table where {constraints}
, and is memory-bloat a concern here?
Scenario
Somewhat similar to ActiveRecord: size vs count, I am working in a Rails app with ActiveRecord models, and have found that calling ar_query.select(1).length
is typically faster than ar_query.count
, and in many cases is a multiple 500+% faster. I'm assuming that the former involves more memory in Rails to process the array than count does, as the latter returns a single scalar directly from the database's COUNT (1) function. The timing difference is a bit counter-intuitive unless there is something under the covers.
This code is used in a highly trafficked area, and can get called many times per second, so performance is key, but I don't want to unnecessarily bog down the site with memory inflation if I don't need to.