0

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.

Community
  • 1
  • 1
Michael
  • 1,786
  • 5
  • 23
  • 42
  • 1
    This question is more a MySQL one than a rails one, I think you should modify it very well to bring the attention of more MySQL gurus on SO. – Tamer Shlash Jun 13 '14 at 03:12
  • 1
    Also see [this](http://stackoverflow.com/q/2710621/368167). – Tamer Shlash Jun 13 '14 at 03:14
  • Thanks @TamerShlash this is great and has set me in the right direction to consider this from a MySQL perspective; the memory issue with calling .length on an array is fairly trivial, so will focus on my needs with the specific queries I'm using. Thanks again. – Michael Jun 13 '14 at 16:58

0 Answers0