| 1 |
# Optimizations and benchmark |
| 2 |
|
| 3 |
*apischema* is (a lot) [faster](#benchmark) than its known alternatives, thanks to advanced optimizations. |
| 4 |
|
| 5 |
 |
| 6 |
 |
| 7 |
|
| 8 |
|
| 9 |
!!! note |
| 10 |
Chart is truncated to a relative performance of 20x slower. Benchmark results are detailed in the [results table](#relative-execution-time-lower-is-better). |
| 11 |
|
| 12 |
## Precomputed (de)serialization methods |
| 13 |
|
| 14 |
*apischema* precomputes (de)serialization methods depending on the (de)serialized type (and other parameters); type annotations processing is done in the precomputation. Methods are then cached using `functools.lru_cache`, so `deserialize` and `serialize` don't recompute them every time. |
| 15 |
|
| 16 |
!!! note |
| 17 |
The cache is automatically reset when global settings are modified, because it impacts the generated methods. |
| 18 |
|
| 19 |
However, if `lru_cache` is fast, using the methods directly is faster, so *apischema* provides `apischema.deserialization_method` and `apischema.serialization_method`. These functions share the same parameters than `deserialize`/`serialize`, except the data/object parameter to (de)serialize. Using the computed methods directly can increase performances by 10%. |
| 20 |
|
| 21 |
```python |
| 22 |
{!de_serialization_methods.py!} |
| 23 |
``` |
| 24 |
|
| 25 |
!!! warning |
| 26 |
Methods computed before settings modification will not be updated and use the old settings. Be careful to set your settings first. |
| 27 |
|
| 28 |
## Avoid unnecessary copies |
| 29 |
|
| 30 |
As an example, when a list of integers is deserialized, `json.load` already return a list of integers. The loaded data can thus be "reused", and the deserialization just become a validation step. The same principle applies to serialization. |
| 31 |
|
| 32 |
It's controlled by the settings `apischema.settings.deserialization.no_copy`/`apischema.settings.serialization.no_copy`, or `no_copy` parameter of `deserialize`/`serialize` methods. Default behavior is to avoid these unnecessary copies, i.e. `no_copy=False`. |
| 33 |
|
| 34 |
```python |
| 35 |
{!no_copy.py!} |
| 36 |
``` |
| 37 |
|
| 38 |
## Serialization passthrough |
| 39 |
|
| 40 |
JSON serialization libraries expect primitive data types (`dict`/`list`/`str`/etc.). A non-negligible part of objects to be serialized are primitive. |
| 41 |
|
| 42 |
When [type checking](#type-checking) is disabled (this is default), objects annotated with primitive types doesn't need to be transformed or checked; *apischema* can simply "pass through" them, and it will result into an identity serialization method, just returning its argument. |
| 43 |
|
| 44 |
Container types like `list` or `dict` are passed through only when the contained types are passed through too (and when `no_copy=True`) |
| 45 |
|
| 46 |
```python |
| 47 |
{!pass_through_primitives.py!} |
| 48 |
``` |
| 49 |
|
| 50 |
!!! note |
| 51 |
`Enum` subclasses which also inherit `str`/`int` are also passed through |
| 52 |
|
| 53 |
### Passthrough options |
| 54 |
|
| 55 |
Some JSON serialization libraries natively support types like `UUID` or `datetime`, sometimes with a faster implementation than the *apischema* one — [orjson](https://github.com/ijl/orjson), written in Rust, is a good example. |
| 56 |
|
| 57 |
To take advantage of that, *apischema* provides `apischema.PassThroughOptions` class to specify which type should be passed through, whether they are supported natively by JSON libraries (or handled in a `default` fallback). |
| 58 |
|
| 59 |
`apischema.serialization_default` can be used as `default` fallback in combination to `PassThroughOptions`. It has to be instantiated with the same kwargs parameters (`aliaser`, etc.) than `serialization_method`. |
| 60 |
|
| 61 |
```python |
| 62 |
{!pass_through.py!} |
| 63 |
``` |
| 64 |
|
| 65 |
!!! important |
| 66 |
Passthrough optimization is a lot diminished with `check_type=False`. |
| 67 |
|
| 68 |
`PassThroughOptions` has the following parameters: |
| 69 |
|
| 70 |
#### `any` — pass through `Any` |
| 71 |
|
| 72 |
#### `collections` — pass through collections |
| 73 |
|
| 74 |
Standard collections `list`, `tuple` and `dict` are natively handled by JSON libraries, but `set`, for example, isn't. Moreover, standard abstract collections like `Collection` or `Mapping`, which are used a lot, are |
| 75 |
not guaranteed to have their runtime type supported (having a `set` annotated with |
| 76 |
`Collection` for instance). |
| 77 |
|
| 78 |
But, most of the time, collections runtime types are `list`/`dict`, so others can be handled in `default` fallback. |
| 79 |
|
| 80 |
!!! note |
| 81 |
Set-like type will not be passed through. |
| 82 |
|
| 83 |
#### `dataclasses` - pass through dataclasses |
| 84 |
|
| 85 |
Some JSON libraries, like [orjson](https://github.com/ijl/orjson), support dataclasses natively. |
| 86 |
However, because *apischema* has a lot of specific features ([aliasing](json_schema.md#field-alias), [flatten fields](data_model.md#composition-over-inheritance---composed-dataclasses-flattening), [conditional skipping](data_model.md#skip-field-serialization-depending-on-condition), [fields ordering](de_serialization.md#field-ordering), etc.), only dataclasses with none of these features, and only passed through fields, will be passed through too. |
| 87 |
|
| 88 |
#### `enums` — pass through `enum.Enum` subclasses |
| 89 |
|
| 90 |
#### `tuple` — pass through `tuple` |
| 91 |
|
| 92 |
Even if `tuple` is often supported by JSON serializers, if this options is not enabled, tuples will be serialized as lists. It also allows easier test writing for example. |
| 93 |
|
| 94 |
!!! note |
| 95 |
`collections=True` implies `tuple=True`; |
| 96 |
|
| 97 |
#### `types` — pass through arbitrary types |
| 98 |
|
| 99 |
Either a collection of types, or a predicate to determine if type has to be passed through. |
| 100 |
|
| 101 |
## Binary compilation using Cython |
| 102 |
|
| 103 |
*apischema* use Cython in order to compile critical parts of the code, i.e. the (de)serialization methods. |
| 104 |
|
| 105 |
However, *apischema* remains a pure Python library — it can work without binary modules. Cython source files (`.pyx`) are in fact generated from Python modules. It allows notably keeping the code simple, by adding *switch-case* optimization to replace dynamic dispatch, avoiding big chains of `elif` in Python code. |
| 106 |
|
| 107 |
!!! note |
| 108 |
Compilation is disabled when using PyPy, because it's even faster with the bare Python code. |
| 109 |
That's another interest of generating `.pyx` files: keeping Python source for PyPy. |
| 110 |
|
| 111 |
## Override dataclass constructors |
| 112 |
|
| 113 |
!!! warning |
| 114 |
This feature is still experimental and disabled by default. Test carefully its impact on your code before enable it in production. |
| 115 |
|
| 116 |
Dataclass constructors calls is the slowest part of the deserialization, about 50% of its runtime! |
| 117 |
They are indeed pure Python functions and cannot be compiled. |
| 118 |
|
| 119 |
In case of "normal" dataclass (no `__slots__`, `__post_init__`, or `__init__`/`__new__`/`__setattr__` overriding), *apischema* can override the constructor with a compilable code. |
| 120 |
|
| 121 |
This feature can be toggled on/off globally using `apischema.settings.deserialization.override_dataclass_constructors` |
| 122 |
|
| 123 |
## Discriminator |
| 124 |
|
| 125 |
[OpenAPI discriminator](json_schema.md#openapi-discriminator) allows making union deserialization time more homogeneous. |
| 126 |
|
| 127 |
```python |
| 128 |
{!discriminator_perf.py!} |
| 129 |
``` |
| 130 |
|
| 131 |
!!! note |
| 132 |
As you can notice in the example, discriminator brings its own additional cost, but it's completely worth it. |
| 133 |
|
| 134 |
## Benchmark |
| 135 |
|
| 136 |
Benchmark code is located [benchmark directory](https://github.com/wyfo/apischema/tree/master/benchmark) or *apischema* repository. |
| 137 |
Performances are measured on two datasets: a simple, a more complex one. |
| 138 |
|
| 139 |
Benchmark is run by Github Actions workflow on `ubuntu-latest` with Python 3.10. |
| 140 |
|
| 141 |
Results are given relatively to the fastest library, i.e. *apischema*; simple and complex results are detailed in the table, displayed result is the mean of both. |
| 142 |
|
| 143 |
#### Relative execution time (lower is better) |
| 144 |
|
| 145 |
{!benchmark_table.md!} |
| 146 |
|
| 147 |
!!! note |
| 148 |
Benchmark use [binary optimization](#binary-compilation-using-cython), but even running as a pure Python library, *apischema* still performs better than almost all of the competitors. |