Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing Object Or Just IDs

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?

like image 771
BeeZee Avatar asked Feb 03 '23 07:02

BeeZee


1 Answers

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 ids but ensures that the objects are of the same type, which you probably want since, for example, if you compared just ids they could be the same even though one is a User and another a Product.

In conclusion, comparing the model objects themselves is best.

like image 142
Andrew Marshall Avatar answered Feb 05 '23 17:02

Andrew Marshall