Ruby on Rails Friday, June 29, 2012

On Jun 29, 4:25 am, Tom Choi <li...@ruby-forum.com> wrote:
> Hello,
>
> I know in ruby that when you want to find the size of your query say
>
> [1,2,3,4,5,6] would provide 6 as the total size, length, or even count.
>
> When I try to use size, length, or count on my application, I would get
> a pretty darn slow performance (takes around 10 seconds to load each
> count and I do it twice). Is there another faster way to get the total
> size from the postgres query?

on an active record scope (which includes associations)

- length will always force all the results to be loaded and then the
length of the array is returned
- count will do a select count(*)
- size will either use the length of the array if it is loaded or do a
count(*) if not

So using length if you don't actually want all the objects loaded will
be way slower.

if a simple count is that slow then you probably want to look at your
database indexes - use explain from the psql console to find out how
it is running your query (on rails 3.2 active record will do this for
you if you've turned on auto explains)

Fred


>
> I am using this kind of format in database
>
> e.g: table population [id, race id]
>      table race [id, persons id]
>      table persons[id, likes]
>
> so if I use "population.race.persons.count" I would get the total size
> of the persons in that particular race and population.
>
> --
> Posted viahttp://www.ruby-forum.com/.

--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to rubyonrails-talk+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en-US.

No comments:

Post a Comment