Uh oh!
There was an error while loading.Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork9.6k
Description
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:
class Category {}class Product {publicfunction__construct(publicCategory$category) {}}$category =newCategory('Shoes');$products = [];for ($i =0;$i <10000;$i++) {$products[] =newProduct($category);}
This creates a collection of 10,000Product
instances, all sharing the exact sameCategory
instance.
Now, when we normalize this collection:
$normalized =$serializer->normalize($products);
TheSerializer
will (as far as I can tell) normalize thesameCategory
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 givenCategory
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:
#[Cacheable(identifier:'id')]class Category {publicint$id;}
It means that even the instances are not the same, we can share a normalized data between differentCategory
instances using the property provided in the attribute.
Benefits
- Improved performance when serializing large collections with shared object references.
- Transparent opt-in via attribute — does not change existing behavior.
- Backward compatible and unobtrusive to current implementations.
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