[Serializer] Add #[Cacheable]
attribute to improve Serializer performance for shared objects
#60540
Labels
#[Cacheable]
attribute to improve Serializer performance for shared objects
#60540
Description
I'd like to share an idea to enhance the performance of the Symfony Serializer component in scenarios where the same object instance is reused multiple times.
Context
Consider the following example:
This creates a collection of 10,000
Product
instances, all sharing the exact sameCategory
instance.Now, when we normalize this collection:
The
Serializer
will (as far as I can tell) normalize the sameCategory
object 10,000 times — once perProduct
— even though its data never changes. This results in unnecessary processing and resource consumption, especially in large datasets or deeply nested structures.Suggested Solution
Introduce a
#[Cacheable]
attribute that signals the serializer to cache and reuse the normalized result of a given object during a normalization cycle. For example:#[Cacheable] class Category {}
With this, the serializer would only normalize a given
Category
instance once and reuse the result for subsequent appearances, as long as it’s the same instance.An additional option to
#[Cacheable]
could be used to specify an identifier to be used as cache key:It means that even the instances are not the same, we can share a normalized data between different
Category
instances using the property provided in the attribute.Benefits
I'd love to hear your thoughts on whether this could fit within the current Serializer architecture or if there's another recommended approach to avoid redundant normalization.
Thanks for considering this!
Example
No response
The text was updated successfully, but these errors were encountered: