38695

rails3 - which is better code for performance

Question:

Which is the best practise and gives me better performance ?

For example:

I have statuses table which have 5 records and each record need to be store on separate variable.

Method1:

@new_status = Status.find_by_status("NEW") @inprocess_status = Status.find_by_status("InProcess") @completed_status = Status.find_by_status("Completed") @occupied_status = Status.find_by_status("Occupied") @success_status = Status.find_by_status("Success")

Method2:

statuses = Status.all @new_status = statuses.find {|status| status.status == "NEW"} @inprocess_status = statuses.find {|status| status.status == "InProcess"} @completed_status = statuses.find {|status| status.status == "Completed"} @occupied_status = statuses.find {|status| status.status == "Occupied"} @success_status = statuses.find {|status| status.status == "Success"}

Or anyother good way ?

Answer1:

This will be even more performant, as it only makes one query to the db and gets only the necessary amount of data. This is assuming status field is unique.

statuses = Status.where( status: ['NEW', 'InProcess', 'Completed', 'Occupied', 'Success'] ).order(:status) @new_status, @completed_status, @inprocess_status, @occupied_status, @success_status = statuses

Answer2:

If there're 5 million records, method 1 should be better because database query has better performance.

If only 5 records, method 2 is better because there's only one database query. Method 1 has 5 queries, which are very time consuming for a small quantity of records.

Answer3:

You have just 5 records so 5 database queries are going to be very expensive, not at all a good practice.

You can fetch them in memory and assign to instance variables. But I can see a symmetry in Method2 and it looks like very symmetrical code. I strongly suggest not to write symmetrical code in ruby, you can modify it with something like:

Status.all.each{|status| instance_variable_set("@#{status.name.downcase}_status" , status ) }

It will create instance variables and initialise your instance variables with respective statuses.

Recommend