Skip to content

Use CompositeDecoder::decodeCollectionSize to pre-allocate collections#3192

Open
fzhinkin wants to merge 12 commits into
devfrom
fzhinkin/collections-initial-capacity
Open

Use CompositeDecoder::decodeCollectionSize to pre-allocate collections#3192
fzhinkin wants to merge 12 commits into
devfrom
fzhinkin/collections-initial-capacity

Conversation

@fzhinkin

@fzhinkin fzhinkin commented May 4, 2026

Copy link
Copy Markdown
Contributor

Reimplemented AbstractCollectionSerializer::merge to read expected collection size first and pass it as an initial capacity to a corresponding builder. Builder were updated to take the capacity into account.

The change is quite intrusive, but for formats providing information about the collection size before reading it (it's only CBOR for now, though) it reduces the footprint and slightly improve decoding performance.

Fixes #3153

Base automatically changed from fzhinkin/cbor-collections-size to dev May 5, 2026 12:00
@fzhinkin
fzhinkin force-pushed the fzhinkin/collections-initial-capacity branch from 1a41b4d to c042815 Compare May 5, 2026 15:59
buffer[position++] = c
}

override fun build() = buffer.copyOf(position)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

To discuss: we can avoid a copy here if position == buffer.size, but we need to explicitly invalidate the builder, JIC.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

builders do not live outside of merge() IIRC

@fzhinkin
fzhinkin marked this pull request as ready for review May 6, 2026 13:42
@fzhinkin
fzhinkin requested a review from Copilot May 6, 2026 13:42

This comment was marked as resolved.

val compositeDecoder = decoder.beginStructure(descriptor)
val expectedSize = compositeDecoder.decodeCollectionSize(descriptor)
val builder = if (previous != null) {
previous.toBuilder().also { it.checkCapacity(expectedSize) }

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This should add the new new "expectedSize" to the current size when calling checkCapacity. The common case for this branch is for incremental parsing of list elements.

It also makes sense to pass the new needed size to toBuilder to avoid an extra copy in the case that a new builder is actually created (not default behaviour).

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice catch, thanks for pointing to it!

Not only the code does not work as expected, it can also fail in runtime if checkCapacity can't handle negative expectedSize (which is the case for all non-empty implementations, I guess).

@fzhinkin
fzhinkin marked this pull request as draft May 6, 2026 21:11
@fzhinkin
fzhinkin marked this pull request as ready for review May 12, 2026 19:45
@fzhinkin

Copy link
Copy Markdown
Contributor Author

Updated benchmarking results:

override fun Array<Element>.toBuilder(expectedAdditionalSize: Int): ArrayList<Element> {
checkBuildersInitialCapacity(expectedAdditionalSize)
val expectedCapacity = size + expectedAdditionalSize.coerceAtLeast(0)
return ArrayList<Element>(expectedAdditionalSize).also { it.addAll(this) }

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should be ArrayList<Element>(expectedCapacity), right?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed

val builder = previous?.toBuilder() ?: builder()
val startIndex = builder.builderSize()
val compositeDecoder = decoder.beginStructure(descriptor)
val expectedSize = compositeDecoder.decodeCollectionSize(descriptor)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I suggest checking that it is not less than -1 right here instead of calling checkBuildersInitialCapacity(initialCapacityHint) in every implementation

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Apparently, I was in the "let's write over 9000 LOC" mood. :/

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed

Comment thread core/commonMain/src/kotlinx/serialization/internal/CollectionSerializers.kt Outdated
val compositeDecoder = decoder.beginStructure(descriptor)
val expectedSize = compositeDecoder.decodeCollectionSize(descriptor)
val builder = if (previous != null) {
previous.toBuilder(expectedSize)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think passing here previous.toBuider(previous.collectionSize() + expectedSize.coerceAtLeast(0)) would also significantly simplify implementations

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe the coerceAtLeast should be 1 (the idea that this would not be called if there is not at least one element added, and the exception would be much less likely than this case).

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Incoming collection can be empty, there's no need to re-allocate existing one in this case

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed

buffer[position++] = c
}

override fun build() = buffer.copyOf(position)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

builders do not live outside of merge() IIRC

override fun Array<Element>.toBuilder(): ArrayList<Element> = ArrayList(this.asList())
override fun Array<Element>.toBuilder(expectedAdditionalSize: Int): ArrayList<Element> {
checkBuildersInitialCapacity(expectedAdditionalSize)
val expectedCapacity = size + expectedAdditionalSize.coerceAtLeast(0)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It may be more optimal to coerce it to at least 1. The use case for extending lists kind of implies to add at least one new element.

val compositeDecoder = decoder.beginStructure(descriptor)
val expectedSize = compositeDecoder.decodeCollectionSize(descriptor)
val builder = if (previous != null) {
previous.toBuilder(expectedSize)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe the coerceAtLeast should be 1 (the idea that this would not be called if there is not at least one element added, and the exception would be much less likely than this case).

@fzhinkin
fzhinkin requested a review from sandwwraith July 10, 2026 14:37
@hfhbd

hfhbd commented Jul 12, 2026

Copy link
Copy Markdown
Contributor

Nice! BTW it's not only CBOR but any 3rd party format too, like my CSV format that returns a List.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

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

5 participants