I have an array called records
with thousand of hashes (see the first array showed below). Every hash contains currently two fields id
and parent_id
. I want to add a new field called updated_at
which is stored in the database (see the second array below).
records = [{"id"=>3, "parent_id"=>2},
{"id"=>4, "parent_id"=>2}]
records = [{"id"=>3, "parent_id"=>2, "updated_at"=>"2014-03-21 20:44:35 UTC"},
{"id"=>4, "parent_id"=>2, "updated_at"=>"2014-03-21 20:44:34 UTC"}]
My first approach is the following one, but it executes a query to the database for every hash, so if I have 1K hashes in the array, it is going to execute 1K queries, which I think is not very good from the performance point of view.
records.each do |record|
record['updated_at'] = Record.find(record['id']).updated_at.utc.to_s
end
Can you suggest me a better solution?
How about this?
May be someone can improvise it better. :)
After doing a lot of benchmarks and trying different algorithms I have come up with a solution that performs very fast and seems it is the most efficient one for now.
The idea is to convert the resulted array of db records into an hash, so finding items into the hash is much faster than doing it into an array.
The time of the results came from benchmarks ran using an array of about 4.5K hashes.
How about something like this? Bulk up the queries by aggregating the ids a slice at a time. Adjust
each_slice
amount to something that performs well...