BeeZee
BeeZee

Reputation: 1602

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?

Upvotes: 9

Views: 1973

Answers (1)

Andrew Marshall
Andrew Marshall

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 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.

Upvotes: 14

Related Questions