Skip to content

Pre-allocate Map and Collection capacities using CBOR definite-length headers #3153

@kozaxinan

Description

@kozaxinan

Currently, when the kotlinx-serialization-cbor library decodes a CBOR map or array, the default MapSerializer and ListSerializer instantiate empty collections (e.g., LinkedHashMap or ArrayList) using their default initial capacities (typically 16).

If a CBOR payload contains a definite-length map or array with thousands of elements, populating the collection triggers continuous, expensive memory reallocations and array-copying under the hood. On memory- and CPU-constrained environments like Android, this creates a noticeable performance bottleneck and unnecessary garbage collection overhead on hot paths.

When the CBOR decoder parses a definite-length map (Major Type 5) or array (Major Type 4), it already reads the exact size from the binary header. The library should use this parsed size to initialize the backing collections with an exact capacity.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions