fix(serialization/msgspec_hooks): avoid dict allocation in default_serializer when no custom type_encoders#4710
Open
Peopl3s wants to merge 1 commit into
Open
fix(serialization/msgspec_hooks): avoid dict allocation in default_serializer when no custom type_encoders#4710Peopl3s wants to merge 1 commit into
Peopl3s wants to merge 1 commit into
Conversation
…rializer when no custom type_encoders
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #4710 +/- ##
==========================================
- Coverage 67.38% 67.38% -0.01%
==========================================
Files 292 292
Lines 14995 14992 -3
Branches 1684 1685 +1
==========================================
- Hits 10105 10102 -3
Misses 4755 4755
Partials 135 135 ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
sobolevn
reviewed
Apr 20, 2026
sobolevn
left a comment
Member
There was a problem hiding this comment.
This is a hot path indeed, do you have a benchmark to prove your optimization? :)
Contributor
Author
|
@sobolevn Yeah, sure (I provided an example benchmark in the issue) from __future__ import annotations
import timeit
from datetime import datetime
from typing import Any
from litestar.serialization.msgspec_hooks import DEFAULT_TYPE_ENCODERS
def default_serializer_before(value: Any, type_encoders=None) -> Any:
type_encoders = {**DEFAULT_TYPE_ENCODERS, **(type_encoders or {})}
for base in value.__class__.__mro__[:-1]:
try:
encoder = type_encoders[base]
except KeyError:
continue
else:
return encoder(value)
raise TypeError(f"Unsupported type: {type(value)!r}")
def default_serializer_after(value: Any, type_encoders=None) -> Any:
encoders = DEFAULT_TYPE_ENCODERS if not type_encoders else {**DEFAULT_TYPE_ENCODERS, **type_encoders}
for base in value.__class__.__mro__[:-1]:
if (encoder := encoders.get(base)) is not None:
return encoder(value)
raise TypeError(f"Unsupported type: {type(value)!r}")
from dataclasses import dataclass
@dataclass
class Record:
id: int
created_at: datetime
name: str
records = [Record(id=i, created_at=datetime.now(), name=f"item-{i}") for i in range(10_000)]
payload = [{"id": r.id, "created_at": r.created_at, "name": r.name} for r in records]
ITERATIONS = 100
def run_before():
for row in payload:
default_serializer_before(row["created_at"])
def run_after():
for row in payload:
default_serializer_after(row["created_at"])
RUNS = 5
results_before = [timeit.timeit(run_before, number=ITERATIONS) for _ in range(RUNS)]
results_after = [timeit.timeit(run_after, number=ITERATIONS) for _ in range(RUNS)]
def stats(label, times):
mn, mx, med = min(times), max(times), sorted(times)[len(times) // 2]
ms = lambda t: f"{t / ITERATIONS * 1000:.2f} ms/iter"
print(f"{label}")
print(f" min={mn:.3f}s ({ms(mn)}) max={mx:.3f}s ({ms(mx)}) median={med:.3f}s ({ms(med)})")
stats("BEFORE", results_before)
stats("AFTER ", results_after)
med_b = sorted(results_before)[RUNS // 2]
med_a = sorted(results_after)[RUNS // 2]
print(f"speedup (median): {med_b / med_a:.2f}x") ┌─────────┬─────────┬─────────┬─────────┐
│ │ min │ median │ max │
├─────────┼─────────┼─────────┼─────────┤
│ BEFORE │ 5.40 ms │ 5.46 ms │ 5.49 ms │
├─────────┼─────────┼─────────┼─────────┤
│ AFTER │ 4.34 ms │ 4.39 ms │ 4.48 ms │
├─────────┼─────────┼─────────┼─────────┤
│ speedup │ 1.24x │ 1.25x │ 1.22x │
└─────────┴─────────┴─────────┴─────────┘ |
Contributor
Author
|
@sobolevn ty for review :) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Description
Avoid dict allocation in default_serializer when no custom type_encoders
Closes #4701
📚 Documentation preview 📚: https://litestar-org.github.io/litestar-docs-preview/4710