Question: Which find gives better performance in Rails, Child.find(child_id) or parent.children.find(child_id)?

Question

Which find gives better performance in Rails, Child.find(child_id) or parent.children.find(child_id)?

Answers 2
Added at 2016-12-16 01:12
Tags
Question

I have 2 models. For the purpose of this Q&A I call them Parent and Child.

# Parent.rb
class Parent < ApplicationRecord
  has_many :children, dependent: :destroy
  # ...
end

# Child.rb
class Child < ApplicationRecord
  belongs_to :parent
  # ...
end

Children resources are nested within the parents resources in the routes file and therefore parent_id will be available in children path.

# routes.rb
resources :parents do
  resources :children
end

In certain actions of children controller such as update and destroy, there's a need to find the corresponding review record by its ID.

From performance standpoint, will it make a material difference between the following 2 sets of statements?

# children_controller.rb
@parent = Parent.find(params[:parent_id])
@child  = Child.find(params[:id])    
# or
@parent = Parent.find(params[:parent_id])
@child  = @parent.children.find(params[:id])    
Answers to

Which find gives better performance in Rails, Child.find(child_id) or parent.children.find(child_id)?

nr: #1 dodano: 2016-12-16 01:12

They are calling the same method.

http://apidock.com/rails/ActiveRecord/FinderMethods/find

Asymptotically, the performance difference is nearly negligible. They are both O(1) in time complexity because you have the primary key, unlike using an indexed column (which would be O(log n)).

If you are really looking to see the tiny bit of differences, @child = Child.find(params[:id]) is faster because there is less code to run. But at the end of the day, it does not matter.

nr: #2 dodano: 2016-12-16 02:12

Assuming you have all the proper indices in place and all that, the only real difference is that there is one more query condition (and hopefully index lookup) if you use the second form @parent.children.find(id).

I always use this form if there's a nested path to ensure that the path is valid. I recommend you do the same.

Source Show
◀ Wstecz