简体   繁体   中英

Optimising ActiveRecord queries in Rails 2.3

I'm performing a query using an sqlite db where I pull out a quite large data set of call records from a database. On the same page I want to show the breakdown of counts per day on the call records, so I perform about 30 count queries on the database.

Is there a way I can filter the set that I retrieve initially and perform the counts on the in memory set, so I don't have to run those continuous queries? I need those counts for graphing and display purposes but even with an index on date, it takes about 10 seconds to run the initial query plus all of the count queries.

What I'm basically asking is there a way to perform the counts on the records returned or perform analysis on it, or is there a smarter way to cache this data?

    @set = Record.get_records_for_range(date1, date2)
while date1 < date2
    @count = Record.count_records_for_date(date1)
    date1 = date1 + 1
end

is basically what I'm doing. Surely there's a simpler and faster way?

Using @set.length will get you the count of the in memory set without querying the database because it is performed by ruby not active record (like .count is)

Read about it here https://batsov.com/articles/2014/02/17/the-elements-of-style-in-ruby-number-13-length-vs-size-vs-count/

Here is a quote pulled out of that article

length is a method that's not part of Enumerable - it's part of a concrete class (like String or Array) and it's usually running in O(1) (constant) time. That's as fast as it gets, which means that using it is probably a good idea.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM