Reputation: 1602
Is there a performance gain in comparing objects like this...
current_user.id == @user.id
versus this ...
current_user == @user
Also are there best-practice reasons for doing one over the other regardless of performance?
Upvotes: 9
Views: 1973
Reputation: 96954
Yes, but barely. ActiveRecord::Base#==
does this:
def ==(comparison_object)
super ||
comparison_object.instance_of?(self.class) &&
id.present? &&
comparison_object.id == id
end
Which essentially compares id
s but ensures that the objects are of the same type, which you probably want since, for example, if you compared just id
s they could be the same even though one is a User
and another a Product
.
In conclusion, comparing the model objects themselves is best.
Upvotes: 14