jpw
jpw

Reputation: 19237

rails 3... in this case two are two queries faster than one?

We'll do this on almost every "hit" to our site. Hosted at Heroku, running Postgres.

Pretty common scenario... a single method in our model gets the COUNT of records matching a condition and also the LAST record matching the same condition.

in realworld use, the COUNT will typically be less than 20. The table has about 20 fields, none are larger than 200 chars.

currently I do TWO queries, n=widget.count(conditions) and then I do z=widget.last(conditions)

but of course I could also do allfound = widget.find(conditions) then get n=allfound.count and z=allfound.last.

Which is "better"? And what are the tradeoffs? (There's always tradeoffs, right?)

Cheers! JP

Upvotes: 0

Views: 283

Answers (2)

wuputah
wuputah

Reputation: 11395

I would stick with two queries because:

  • Don't prematurely optimize - until you NEED to optimize this, stick with what you need to do, not what is (or seems) fastest.
  • If the table doesn't change, your RDBMS can cache the queries/results anyway, so the queries will not even touch disk (in either case).
  • It's better to cache (e.g. to memcached) the two individual values to reduce it to zero queries instead of caching the entire table in memcached.
  • Even if one query was faster due to round-trip time to the database, the time it would take Rails to instantiate the extra records (just for you to throw most of them away) would likely compensate for the time to do two queries. That said, with two queries, Rails will have to prepare both of them, which will also take time.

If you really want to know the real answer, the only way to know for sure is to benchmark it. Create a Rake task that does the benchmark and then run it on Heroku.

Upvotes: 1

Robin
Robin

Reputation: 21884

Did you check the logs? Are you sure Rails wont do 2 queries as well in the second case?

Upvotes: 0

Related Questions