Skip to content

Reuse private candidate lists for hard entity collisions - #811

Draft
FurryMileon wants to merge 1 commit into
CaffeineMC:developfrom
FurryMileon:perf/collision-query-allocations
Draft

FurryMileon wants to merge 1 commit into
CaffeineMC:developfrom
FurryMileon:perf/collision-query-allocations

Conversation

@FurryMileon

@FurryMileon FurryMileon commented Nov 21, 2026 •

Copy link
Copy Markdown

AI wrote all the code in this PR, and there may be bugs the tests didn't catch. I'm sharing it as a prototype in case you want to try something similar in Lithium. Feel free to take the idea in a different direction or close the PR.

Proposed changes

appendEntityCollisions and doesBoxCollideWithHardEntities build an entity list for immediate use. The boolean query also creates a lazy iterable and an iterator just to call hasNext(). This patch reuses one private ArrayList<Entity> per calling thread on the class-group path and checks for the first hard collision without those iterator wrappers. There are no new mixins, settings, threads or dependencies.

  • The query still collects section entities first and platform multipart entities second, before running any collision callbacks. If a callback moves or removes another entity, that entity is still in the candidate list. The boolean check keeps its original short-circuit, EPSILON handling, canCollideWith/canBeCollidedWith, getBoundingBox() and Shapes.create(...) calls. The append path still produces every accepted shape in order.
  • A nested query cannot borrow the outer list, even while it's empty. finally clears the references before returning the list for reuse. After a query with more than 256 candidates, the buffer is discarded. The cutoff applies to the result size; the backing array can be larger.
  • The three-argument public query still returns its own result. The patch doesn't cache caller-visible lists, change getPushableEntities, or clear a list supplied by vanilla or another EntityGetter. The append fallback keeps the delegate's iterator. The public lazy shape iterable is not pooled.

Allocation and time

The benchmarks ran on a dedicated Minecraft 26.3 server with Fabric Loader 0.19.5, a Ryzen 9 7950X3D, Temurin 25.0.5.1+2, G1, a 1 GiB heap and four active JVM processors with fixed CPU affinity. A and B were local source builds of the base commit and the patch. Eight fresh JVMs ran in ABBA BAAB order with identical non-Lithium inputs.

Each case ran directly on the server thread against real entities and sections: two warmup rounds, then five measured rounds of 16,384 calls each per JVM. Bytes per call come from the thread allocation counter. Times are medians of the per-process medians.

Hard collision query Candidates Base B/call Patched B/call Base ns/call Patched ns/call
Any? 0 208 96 42.1 34.8
Any? 1 344 176 58.3 52.1
Any? 2 344 176 115.6 108.1
Append shapes 0 120 96 34.0 35.6
Append shapes 1 256 176 55.5 54.7
Append shapes 2 336 256 124.4 125.6

The six allocation results repeated in every JVM of the corresponding variant. Unmodified push-query controls had identical allocation medians (104 / 160 / 344 B/call for 0 / 1 / 18 matches), though timings varied. Empty appends saved 24 B but were about 1.7 ns slower here.

Whole-server workload

The pen held 96 live cows and eight boats across section boundaries, with fixed initial positions and IDs, normal physics and AI, and no players. Each JVM warmed up for 10,000 ticks, then ran 6 × 4,000 requested ticks under JFR. A separate 512-tick /perf window recorded individual tick times. The tracked cow advanced 24,006 ticks over the 24,000 requested in every JVM (six boundary ticks). AI trajectories could differ between runs.

Per-process metric, median of four JVMs per variant Base Patched
Approximate server-thread B/requested tick 480,267 469,798
Median reported sprint MSPT 0.3275 0.3300
/perf p50 (ms) 0.901 0.914
/perf p95 (ms) 1.226 1.267
/perf p99 (ms) 2.252 2.256

The median server-thread allocation per tick was 2.18% lower. Two paired comparisons went each way, and the JFR counter samples bracketed the sprint rather than lining up exactly with its boundaries. These runs didn't show a whole-server speedup, shorter GC pauses or better tail latency. Client FPS and player, network and region workloads weren't measured.

Behavioral verification

All 16 scenarios matched unmodified Lithium. The 14 that could also be compared with vanilla matched there too; the other two check Lithium's existing early exit. Collision order stayed the same with 320 boats and with Ender Dragon parts.

All 38 JUnit tests passed on Fabric. All 34 required GameTests passed on both Fabric and NeoForge. The optional lava_push_speed test failed with and without the patch.

Keep collection ahead of collision callbacks and leave caller-owned query results and the vanilla fallback untouched.

Allow nested queries to allocate independently, release the per-thread list in finally, and discard dense snapshots instead of retaining their backing array.

Check for the first hard collision directly while preserving the bounding-box and shape hooks.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟢 Approval recommended

No active review issues are recorded for the collision-query candidate-list reuse changes.

No open issues 🎉

What changed in this PR

This PR reduces temporary allocations in Lithium’s hard-entity collision queries by reusing private, per-thread candidate lists while preserving ownership of caller-visible results.

Changes:

  • Adds scratch-list support to entity collection while retaining fallback behavior.
  • Shares collision-processing logic between boolean and append queries, avoiding iterator wrappers for boolean checks.
  • Handles nested queries and buffer cleanup, discards oversized buffers, and documents list ownership.
File Description
common/​src/​main/​java/​net/​caffeinemc/​mods/​lithium/​common/​world/​WorldHelper.java Adds a scratch-list overload and consolidates entity collection.
common/​src/​main/​java/​net/​caffeinemc/​mods/​lithium/​common/​services/​PlatformEntityAccess.java Documents multipart ordering and caller ownership; no functional change.
common/​src/​main/​java/​net/​caffeinemc/​mods/​lithium/​common/​entity/​LithiumEntityCollisions.java Reuses thread-local candidate buffers and directly checks hard collisions.
CHANGELOG.md Records the candidate-list reuse optimization.

Review effort: Balanced

@2No2Name

Copy link
Copy Markdown
Member

Getting rid of the Iterable that is only used for hasNext is okay, but in total this adds more complexity than it removes. 0.0025mspt improvement with 100 entities doesn't justify it

@FurryMileon

FurryMileon commented Nov 25, 2026 •

Copy link
Copy Markdown
Author

Getting rid of the Iterable that is only used for hasNext is okay, but in total this adds more complexity than it removes. 0.0025mspt improvement with 100 entities doesn't justify it

The main goal of this PR was to share an optimization idea: reducing repeated allocations of temporary objects by reusing buffers. I was inspired by a C# example in this video at 9:03, which made me wonder whether a similar idea could be useful in Java. This PR is a prototype exploring that through reusing temporary candidate lists for collision queries.

@2No2Name
2No2Name marked this pull request as draft November 30, 2026 06:31

This branch has not been deployed

No deployments
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.

3 participants