Skip to content

BaseMapCodec.decode(): fix O(N²) complexity - #110

Open
nekotxs wants to merge 1 commit into
Mojang:masterfrom
nekotxs:master
Open

BaseMapCodec.decode(): fix O(N²) complexity#110
nekotxs wants to merge 1 commit into
Mojang:masterfrom
nekotxs:master

Conversation

@nekotxs

@nekotxs nekotxs commented Aug 2, 2026

Copy link
Copy Markdown

In #88, ImmutableMap.Builder was replaced by Object2ObjectArrayMap. Using putIfAbsent() on each element causes O(N²) complexity.

I made some measurements and provided some context.

On pure vanilla it doesn't cause a lot of issues, but if you add some datapacks or mods with advancements, it can cause disastrous lags of up to several seconds on each player join, when advancements are loaded.

The easiest solution would be to replace Object2ObjectArrayMap with Object2ObjectOpenHashMap, though it can be less performant on N<=2.

I suggest using ImmutableMap.Builder with buildOrThrow() as the default path, with a fallback to Object2ObjectOpenHashMap if any failures (including duplicate keys) are present. This makes sense since failures are rare in practice (I measured 0.004% of calls encountering a failure on a moderately modded server, and none on vanilla). This would give better performance than both Object2ObjectArrayMap and Object2ObjectOpenHashMap in the common, failure-free case. The fallback path takes longer than plain Object2ObjectOpenHashMap, but it still has acceptable time and O(N) complexity.

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.

1 participant