Move exclude logic to improve performance #241
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.
Hi!
I'm dealing with dataclasses that contain lists and numpy arrays that are very large but are excluded when encoding to JSON. Unfortunately, these lists and arrays make the serialization take a very long time despite being excluded. This appears to be due to
_asdict
running recursively on each list/array item before theexclude
predicate is checked.Unless I'm missing something, it's not possible to control this from outside the library, so I moved the logic that checks the
exclude
predicate to_asdict
– before the function calls itself recursively on the items of the excluded field.With a dataclass that contains a few simple fields as well as an excluded
List[int]
of length 10 000 000, this reduced the encoding time from over 30 seconds to a small fraction of a second on my machine.