Rails and queries

I noticed that rails doubles query times.

It performs a query once as a subquery like so: select count(*) from
(actual_query) as countQuery;

Then it performs the actual_query.

Effectively doubling the performance hit due to querying.

Most of the time this isn’t that big a deal, but when you start doing
more in depth queries it adds up quick.

For example, I have a 1.5s query on a page that takes .13s to render.
After rails is done, the db hit is over 3s.

1.5s is really not that bad. But 3s+ begins to be very noticeable.

My questions are:

  1. It would appear that the data gained from the second query is saved
    (obviously) or we wouldn’t be able to work on it. Why not gain the
    count from the results on the application level instead of doing a
    double query for the same?

  2. Rails also repeats the entire process on each page load in
    pagination. Why not do this once and cache the data?

Most of the time this isn’t that big a deal, but when you start doing
(obviously) or we wouldn’t be able to work on it. Why not gain the
count from the results on the application level instead of doing a
double query for the same?

  1. Rails also repeats the entire process on each page load in
    pagination. Why not do this once and cache the data?

How do you propose Rails cache it? An in-memory hash? Memcache?
Fragment caching the output? This is application specific, so you
should cache it in a way that makes sense for your app. If you come
up with what you believe is the One True Way that’s better than what
rails provides, make it a plugin and get other folks using it.


Rick O.
http://weblog.techno-weenie.net
http://mephistoblog.com