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

Reduce allocations in BelongsToAssociation#replace_keys #51754

Merged
merged 1 commit into from May 7, 2024

Conversation

casperisfine
Copy link
Contributor

Using the same benchmark as in #51726

replace_keys always allocate a multiple arrays to support composite primary keys, even though most primary keys likely aren't composite.

And even when they are, we can avoid needless allocations by not using Array#zip.

This reduce allocations by 18% (8k) on that benchmark.

Before:

Total allocated: 4.88 MB (44495 objects)
Total retained: 4.16 MB (32043 objects)

allocated memory by file
-----------------------------------
...
 320.00 kB  activerecord/lib/active_record/associations/belongs_to_association.rb

allocated objects by file
-----------------------------------
...
      8000  activerecord/lib/active_record/associations/belongs_to_association.rb

After:

Total allocated: 4.56 MB (36495 objects)
Total retained: 4.16 MB (32041 objects)

NB: belongs_to_association doesn't show up in top files anymore

Using the same benchmark as in rails#51726

`replace_keys` always allocate a multiple arrays to support composite
primary keys, even though most primary keys likely aren't composite.

And even when they are, we can avoid needless allocations by not using
`Array#zip`.

This reduce allocations by 18% (8k) on that benchmark.

Before:

```
Total allocated: 4.88 MB (44495 objects)
Total retained: 4.16 MB (32043 objects)

allocated memory by file
-----------------------------------
...
 320.00 kB  activerecord/lib/active_record/associations/belongs_to_association.rb

allocated objects by file
-----------------------------------
...
      8000  activerecord/lib/active_record/associations/belongs_to_association.rb
```

After:

```
Total allocated: 4.56 MB (36495 objects)
Total retained: 4.16 MB (32041 objects)
```

NB: `belongs_to_association` doesn't show up in top files anymore
@byroot byroot merged commit d7980c6 into rails:main May 7, 2024
3 of 4 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants