Skip to content

[Serializer] Add #[Cacheable] attribute to improve Serializer performance for shared objects #60540

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

Open
tsantos84 opened this issue May 25, 2025 · 0 comments

Comments

@tsantos84
Copy link
Contributor

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 {
    public function __construct(public Category $category) {}
}

$category = new Category('Shoes');
$products = [];

for ($i = 0; $i < 10000; $i++) {
    $products[] = new Product($category);
}

This creates a collection of 10,000 Product instances, all sharing the exact same Category instance.

Now, when we normalize this collection:

$normalized = $serializer->normalize($products);

The Serializer will (as far as I can tell) normalize the same Category object 10,000 times — once per Product — 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:

#[Cacheable(identifier: 'id')]
class Category {
    public int $id;
}

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

  • 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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants