Low-Level Core Optimizations
Internal hot-path optimizations across Netty Connection, ServerChunkCache, CraftPlayer.canSee(), Commodore, PaperEventManager, PluginPackageIndex, and packet filtering.
Besides configurable kill-switches, Apis includes low-level patches on hot execution paths in Paper and Minecraft to cut allocations, JVM exceptions, thread handoffs, and network traffic.
1. Outbound Packet Batching in Connection (Netty EventLoop)
Section titled “1. Outbound Packet Batching in Connection (Netty EventLoop)”Patch: net/minecraft/network/Connection.java.patch
Normally, sending a burst of small packets from main-thread schedules a separate eventLoop().execute(...) task per packet. Apis adds a buffered batch queue guarded by a lightweight outboundBatchLock:
- Packets sent from off the Netty EventLoop without
flushaccumulate insidebatchPackets/batchListeners. - Initial capacity is 16 entries, with an auto-drain threshold (
MAX_BATCH_SIZE_BEFORE_DRAIN) of 256 packets. - Arrays are pooled via
spareBatchPackets/spareBatchListenersto avoid GC churn. - Batches force-flush (
flushOutboundBatch) insideflush(),tick(), upon hitting 256 items, and right beforescheduleNettyTaskto keep strict FIFO ordering. - On disconnect (
disconnect()/clearPacketQueue()), pending batches drain cleanly and invokeonPacketDispatchFinish.
2. Direct 4-Slot Cache in ServerChunkCache
Section titled “2. Direct 4-Slot Cache in ServerChunkCache”Patch: net/minecraft/server/level/ServerChunkCache.java.patch
Vanilla ServerChunkCache shifts its 4-entry arrays (lastChunkPos / lastChunkStatus / lastChunk) on every chunk lookup miss. Apis swaps that for a direct O(1) hash slot with zero array shifts:
private static int cacheSlot(final int x, final int z) { return ((x & 1) | ((z & 1) << 1)) & 3;}- Computes the slot in two bitwise ops for adjacent 2x2 chunks (
getFullChunkCached,storeInCache). - To stay safe when chunks unload from worker threads, a
volatileoffThreadCacheInvalidatedflag triggers cache cleanup on the main thread insidemoonrise$setFullChunk,getChunk,getChunkNow, andgetChunkAtIfLoadedImmediately.
3. Fast-Path for CraftPlayer.canSee()
Section titled “3. Fast-Path for CraftPlayer.canSee()”Patch: org/bukkit/craftbukkit/entity/CraftPlayer.java.patch
CraftPlayer tracks a boolean hasHiddenEntities = !this.invertedVisibilityEntities.isEmpty(), kept up to date across hideEntity0, showEntity0, unregisterEntity, showEntity, and onEntityRemove.
- When
!this.hasHiddenEntities(true whenever a player has no per-entity hides),canSee(Entity)returnsentity.isVisibleByDefault()directly, skipping bothentity.getUniqueId()and theHashMaplookup.
4. Lazy Commodore & Byte-Level Constant Pool Pre-Scan
Section titled “4. Lazy Commodore & Byte-Level Constant Pool Pre-Scan”Patches: org/bukkit/craftbukkit/util/Commodore.java.patch, CraftMagicNumbers.java.patch, CraftServer.java.patch
Plugin bytecode rewriting via ASM (ClassReader / ClassWriter) is one of the heaviest steps during plugin loading:
CraftMagicNumbers:commodoreinitializes lazily on first actual demand (synchronized getCommodore()). Ifcompatibility.legacy.plugin-bytecode-reroutingisfalse, bytecode rewriting is skipped completely.Commodore.mayNeedConversion: before touching ASM, a zero-allocation byte scanner parses the.classheader (0xCAFEBABE) andconstant pool. It scansCONSTANT_Utf8entries fororg/bukkit/,org/spigotmc/,com/destroystokyo/,io/papermc/,com.mysql.jdbc.Driver(plusjava/lang/Enum,java/util/EnumSet,java/util/EnumMap, andcom/google/common/whenenum-compatibility-mode <= 1.20.6). No match means ASM never runs.selectRenames(pluginVersion): instead of allocatingnew HashMap<>(RENAMES)per class, it picks one of the prebuilt immutable maps (RENAMES_WITH_COW,RENAMES_WITH_CUBE_MOB,RENAMES_WITH_COW_AND_CUBE_MOB).
5. PaperEventManager & Event Listener Optimizations
Section titled “5. PaperEventManager & Event Listener Optimizations”Patches: io/papermc/paper/plugin/manager/PaperEventManager.java.patch, ServerGamePacketListenerImpl.java.patch
getRegistrationClassviaClassValue: replaces recursiveclazz.getDeclaredMethod("getHandlerList")calls (which throw and catchNoSuchMethodExceptionat each hierarchy level) with aClassValue<Class<? extends Event>> EVENT_REGISTRATION_CLASSEScache scanningcurrent.getDeclaredMethods()(name.equals("getHandlerList") && parameterCount == 0).createRegisteredListenerswithoutSets.union: drops twoImmutableSetallocations andSets.union(Set.of(...), Set.of(...))in favor of a pre-sizedArrayListholdingdeclaredMethodsplus inheritedpublicMethods(pub.getDeclaringClass() != listenerClazz).PlayerJumpEventfast-path: inServerGamePacketListenerImpl#handlePlayerPositionChange,Location from,Location to, andPlayerJumpEventare only allocated ifPlayerJumpEvent.getHandlerList().hasListeners()istrue.PlayerMoveEventfast-path: inServerGamePacketListenerImpl(handleMoveVehicleandhandleMovePlayer),Location from,Location to, and event dispatch are skipped wheneverPlayerMoveEvent.getHandlerList().hasListeners()isfalse. Tracking coordinates (updateLastEventPosIfMoved) still update properly so later listener registration will not misfire.
6. O(1) Package Indexing (PluginPackageIndex)
Section titled “6. O(1) Package Indexing (PluginPackageIndex)”Patches: ConfiguredPluginClassLoader.java.patch, PluginPackageIndex.java.patch, PluginClassLoader.java.patch, PaperPluginClassLoader.java.patch, PaperSimplePluginClassLoader.java.patch, SimpleListPluginClassLoaderGroup.java.patch, SpigotPluginClassLoaderGroup.java.patch
When resolving cross-plugin classes in SimpleListPluginClassLoaderGroup, upstream Paper walks through plugin classloaders looking up .class entries in every JAR. In Apis:
- On startup,
PluginPackageIndex.fromJar(jar, libraryLoader)scans the plugin JAR and libraryURLClassLoaderentries once (includingMETA-INF/versions/), storing package names in aConcurrentHashMap.newKeySet(). - Inside
getClassByName, any loader wheremayContainPackage(loader, packageName) == falseis skipped in O(1). - Runtime codegen fallback: if a class is not found and at least one loader was skipped (
anySkipped), a fallback scan runs only over the skipped loaders (supporting ByteBuddy / ASM /defineClassruntime classes). Matches register viarecordDynamicPackage(...)for subsequent lookups.
7. Distance-Based Packet Clamping (packet-range-clamping)
Section titled “7. Distance-Based Packet Clamping (packet-range-clamping)”Patches: ChunkMap.java.patch, ServerEntity.java.patch, LivingEntity.java.patch, ServerLevel.java.patch
When network.packet-range-clamping.full-packet-broadcast is set to false in configs/apis.yml, Apis caps broadcast distance for noisy packets in dense lobbies and spawns:
| Packet Type | configs/apis.yml Key |
Default (Range) | Implementation |
|---|---|---|---|
Projectiles (Projectile) |
projectile-tracking-range |
32 ([0, 256]) |
ChunkMap.TrackedEntity#getEffectiveRange() via clampEntityTrackingRange |
Armor / Equipment (ClientboundSetEquipmentPacket) |
armor-equipment-range |
32 ([0, 256]) |
ServerEntity#sendPairingData and LivingEntity#updatePlayersWithNewEquipment (sendToTrackingPlayersFiltered with canSee check) |
Particles (sendParticles) |
particle-broadcast-range |
16.0 ([0.0, 256.0]) |
ServerLevel#sendParticles via shouldDropParticlePacket |
8. Additional Engine Tweaks
Section titled “8. Additional Engine Tweaks”- Lazy
DefaultAttributes(DefaultAttributes.java.patch): instead of loading ~90 mob classes and buildingAttributeSuppliermaps at boot, attributes build on first use viaSUPPLIER_FACTORIESand cache in aConcurrentHashMap. - Disable NUMA/JNA outside Linux (
OSNuma.java,MoonriseConstants.java.patch,MoonriseCommon.java.patch,Util.java.patch): macOS and Windows selectOSNuma.NoOp.INSTANCE(NUMA_ENABLE = false) immediately without loadingLinuxNumaor JNA. - Lazy native cipher (
Natives.java,ServerConnectionListener.java.patch):Natives.cipherloads only whenserver.usesAuthentication()istrue, skipping native cryptodlopenbehind Velocity/BungeeCord proxies.