Skip to content

Avoid allocating temporary basic_json for cbor and msgpack object keys - #5328

Open
alexprabhat99 wants to merge 4 commits into
nlohmann:developfrom
alexprabhat99:5318-cbor-msgpack-object-key-allocations
Open

Avoid allocating temporary basic_json for cbor and msgpack object keys#5328
alexprabhat99 wants to merge 4 commits into
nlohmann:developfrom
alexprabhat99:5318-cbor-msgpack-object-key-allocations

Conversation

@alexprabhat99

Copy link
Copy Markdown
Contributor

This PR optimizes CBOR and MessagePack serialization by avoiding the construction of a temporary basic_json object for every object key during serialization.

Previously, object keys were passed through write_cbor()/write_msgpack(), which expected a BasicJsonType and therefore implicitly constructed a temporary basic_json for each key. This introduced unnecessary heap allocations during serialization.

This change factors out the string serialization logic into dedicated helper functions and serializes object keys directly. The implementation preserves compatibility with custom object key types while eliminating the extra basic_json allocations for the common case where object_t::key_type is string_t.

A regression test has been added to verify compatibility with custom object key types.

Fixes #5318

@github-actions

This comment was marked as outdated.

Signed-off-by: alexprabhat99 <alexpbara@gmail.com>
Signed-off-by: alexprabhat99 <alexpbara@gmail.com>
Signed-off-by: alexprabhat99 <alexpbara@gmail.com>
Signed-off-by: alexprabhat99 <alexpbara@gmail.com>
@alexprabhat99
alexprabhat99 force-pushed the 5318-cbor-msgpack-object-key-allocations branch from 38a5640 to d10514d Compare July 28, 2026 16:34
@alexprabhat99

Copy link
Copy Markdown
Contributor Author

Hi @nlohmann
All checks are successful now.
Thanks!

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

to_cbor()/to_msgpack() allocate a temporary basic_json for every object key

1 participant