1

Rails3 - which is a better code for performance

 2 years ago
source link: https://www.codesd.com/item/rails3-which-is-a-better-code-for-performance.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Rails3 - which is a better code for performance

advertisements

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 ?


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


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK