Skip to content

Only dup reflections that are serialized - #2501

Open
sucicfilip wants to merge 2 commits into
rails-api:0-10-stablefrom
sucicfilip:dup-only-requested-reflections
Open

sucicfilip wants to merge 2 commits into
rails-api:0-10-stablefrom
sucicfilip:dup-only-requested-reflections

Conversation

@sucicfilip

Copy link
Copy Markdown

Purpose

Serializer#associations deep-dups every class reflection on each serializer instance, even the ones it then skips because of excluded? or the include directive. With sparse fieldsets most reflections are skipped, so most of those copies are thrown away right after they are made.

Changes

  • Iterate self.class._reflections and dup each reflection lazily, once it passes excluded? and include_directive.key?.
  • The copy is memoized per serializer instance by key, so repeated associations calls reuse it, same as before.
  • The per-instance copy from Thread unsafe behavior #2270 stays, so the thread-safety fix is unchanged. excluded? and key? only read the class reflection, they don't mutate it.

Caveats

excluded? still runs before include_directive.key?, so if:/unless: conditions are evaluated for unrequested associations like before. Swapping the two checks would remove most of the remaining cost, but it changes when user conditions run, so I left it out.

Related GitHub issues

#2270

Additional helpful information

1000 PORO records, JSON:API adapter, fields: { posts: [:name] }, belongs_to associations, none requested. Ruby 3.4.7, Rails 8.1, median of 40 renders, 3 processes each:

associations 0.10.16 this PR
0 37.2 ms 36.3 ms
20 51.4 ms 43.4 ms

Allocations per record with 20 associations: 111 -> 90.

sucicfilip and others added 2 commits November 8, 2026 10:30
Serializer#associations deep-duped every class reflection on each
serializer instance, even ones skipped by `excluded?` or the include
directive. Dup each reflection lazily, once it passes both checks.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant