This commit is contained in:
nlohmann
2026-08-04 07:02:38 +00:00
parent ce3ce5a2b8
commit 3de3beb9b0
263 changed files with 462 additions and 287 deletions
File diff suppressed because one or more lines are too long
+33
View File
@@ -58,6 +58,39 @@ The type uses a `std::vector` to store object elements. Therefore, adding elemen
- **find**
- **insert**
## Complexity
Because the elements are stored in a `std::vector` in insertion order, there is no index to look a key up by. Every key-based operation performs a **linear scan** over the stored elements. With `n` denoting the number of elements in the container:
| Operation | Complexity | Note |
| -------------------------------------- | -------------- | -------------------------------------------------------- |
| **emplace** | O(n) | scans for an existing key, then appends (amortized O(1)) |
| **operator[]** | O(n) | delegates to **emplace** (non-const) or **at** (const) |
| **at** | O(n) | throws `std::out_of_range` if the key is not found |
| **find** | O(n) | |
| **count** | O(n) | the result is always 0 or 1 |
| **erase(key)** | O(n) | scan, then move the remaining elements one position down |
| **erase(pos)**, **erase(first, last)** | O(n) | moves all elements after the erased range |
| **insert(value)** | O(n) | equivalent to **emplace** |
| **insert(first, last)** | O((n + m) * m) | for `m` inserted elements |
This differs from `std::map`, where the same operations are O(log n).
Quadratic cost of building large objects
Because every insertion scans all elements inserted so far, building an object of `n` distinct keys costs **O(n²)** in total. This applies to filling an [`ordered_json`](https://json.nlohmann.me/api/ordered_json/index.md) object key by key as well as to parsing one, since the parser inserts each key as it is read.
The cost is negligible for the object sizes typically found in configuration files or API payloads, but it grows steeply for machine-generated objects with many thousands of keys. Measured with `-O2 -DNDEBUG` for parsing a flat object of `n` keys, relative to `nlohmann::json` (which uses `std::map`):
| `n` | `json` | `ordered_json` | factor |
| ------ | ------ | -------------- | ------ |
| 2000 | 0.7 ms | 3.6 ms | 5× |
| 4000 | 0.8 ms | 14.0 ms | 19× |
| 8000 | 1.6 ms | 67.8 ms | 43× |
| 16 000 | 3.3 ms | 181.6 ms | 54× |
If key order matters for objects of that size, consider a container with a lookup index, such as [`tsl::ordered_map`](https://github.com/Tessil/ordered-map) ([integration](https://github.com/nlohmann/json/issues/546#issuecomment-304447518)), as the object type -- see [object order](https://json.nlohmann.me/features/object_order/index.md).
## Examples
Example