Improve performance of fields_for method with memoization #2474
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.
Description
This PR implements memoization to improve the performance of the
fields_for
method in theActiveModel::Serializer::Fieldset
class.I found that this gem calls #fields_for method multiple times.
Motivation and Context
The current implementation of
fields_for
performs string manipulations and hash lookups on every call. By memoizing the results, we can significantly reduce redundant operations, especially when the method is called frequently with the sametype
.How Has This Been Tested?
The existing test suite was run before and after the changes. All tests pass, and there's a noticeable performance improvement:
Without memoization:
Finished in 2.639453s, 217.8482 runs/s, 377.7298 assertions/s.
With memoization:
Finished in 2.465571s, 233.2117 runs/s, 404.3688 assertions/s.
Types of changes
Checklist: