Question

I have two ways of doing a similar thing and would like to know: 1. Which is less 'demanding' of the database?, 2. Which is faster?, 3. Which takes up less memory?, and 4. If there are any other issues I need to consider when comparing the two.

Basically, I have an Event model that has_many Exchanges. I need the exchanges for an event sorted by type 'long' and 'short'. The first way is like so:

@event.exchanges.each do |ex|
  if ex.short == true
    @sells << [ex.price, ex.quantity]
  else
    @buys << [ex.price, ex.quantity]
  end
end

The other ways is to set scopes on the Exchange model for short and long types and sort the exchanges like so:

@sells = @event.exchanges.shorts
@buys = @event.exchanges.longs

The second way is more concise and easier to read. But it would seem like ActiveRecord has to 'cycle' through all the exchanges twice. I was using the first way because I wanted to minimize the times Rails accesses the database. But I might be misunderstanding how databases work. I'm also (blindly) guessing that the second way takes up more memory as you get the entire object when I really just need two attributes from each (like the first method gives).

Am I understanding this correctly or way off? Are there other factors I should be considering too?

----- Edited in Schema ----- This is the schema for the Event & Exchange models:

create_table "events", :force => true do |t|
  t.string   "title"
  t.text     "description"
  t.integer  "last_price"
  t.integer  "outcome"
  t.boolean  "closed"
  t.datetime "created_at"
  t.datetime "updated_at"
end

create_table "exchanges", :force => true do |t|
  t.integer  "event_id"
  t.integer  "user_id"
  t.integer  "price"
  t.integer  "quantity"
  t.boolean  "short"
  t.datetime "created_at"
  t.datetime "updated_at"
end
Was it helpful?

Solution

Benchmarking it is the only way to know for sure, but your first example has ruby looping through each row of the query to build up two arrays while the second example has the database aggregate the results and return them in one step.

You could use the rails benchmarker to find out for sure, but my personal instinct would be for "reasonable conditions" (whatever THAT means) you'd be better off letting the db do the heavy lifting and get two arrays back instead of letting the database return a single array, loop over every element, and for each element to a value test and an array addition.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top