Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Store the resource_klass and id in an array for efficiency #1428

Merged
merged 1 commit into from
Jan 13, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 12 additions & 6 deletions lib/jsonapi/resource_identity.rb
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,17 @@ module JSONAPI
# rid = ResourceIdentity.new(PostResource, 12)
#
class ResourceIdentity
attr_reader :resource_klass, :id

# Store the identity parts as an array to avoid allocating a new array for the hash method to work on
def initialize(resource_klass, id)
@resource_klass = resource_klass
@id = id
@identity_parts = [resource_klass, id]
end

def resource_klass
@identity_parts[0]
end

def id
@identity_parts[1]
end

def ==(other)
Expand All @@ -27,11 +33,11 @@ def ==(other)
end

def eql?(other)
other.is_a?(ResourceIdentity) && other.resource_klass == @resource_klass && other.id == @id
hash == other.hash
end

def hash
[@resource_klass, @id].hash
@identity_parts.hash
end

def <=>(other_identity)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Interesting that eql? and <=> diverge in what they compare but is out of scope to this change

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For <=> it really should be comparing the resource_klasses first and then the ids second to determine the response. I think that would only affect the ordering of identities in the related identities when we're using a SortedSet and storing identities for a polymorphic relationship. It looks like that comparison can be done without any allocations so it's probably a good idea to make the change, but I'll handle that in a separate PR.

Expand Down