Improve GraphQL::Dataloader::Source#sync's efficiency #4519
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Summary
In the discussion #4512, we discovered an issue with
sync
related tographql-ruby/lib/graphql/dataloader/source.rb
Line 74 in 250a724
When the
pending_keys
, which is a duplicate of@pending_keys
, becomes large, it tends to consume much Ruby CPU resources, particularly when dealing withActiveRecord
as aSource
key.This PR modify the function of
sync
so that it only waits for the key on whichload
was called.graphql-ruby/lib/graphql/dataloader/source.rb
Line 37 in 250a724
graphql-ruby/lib/graphql/dataloader/source.rb
Line 49 in 250a724
Benchmark
In the benchmark, I use
Struct
as aSource
key , and load 5000Struct
objects.In Ruby 2.7.8, this approach is ~9.49x faster than before but it increases ~0.21% memory. In Ruby 3.0.6, this approach is ~4.99x faster than before but it increases ~0.22% memory.
Benchmark Script
Ruby 2.7.8
Before
After
Ruby 3.0.6
Before
After